package com.quanyan.place.service.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.PlatformTypeEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.common.utils.UUIDUtils;
import com.quanyan.orderpay.request.ReqOrderRefund;
import com.quanyan.orderpay.request.ReqOrderSave;
import com.quanyan.orderpay.request.ReqPayInfo;
import com.quanyan.orderpay.request.ReqProductDetail;
import com.quanyan.orderpay.request.ReqRefundPayInfo;
import com.quanyan.orderpay.request.ReqRefundProduct;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.OrderStatusEnum;
import com.quanyan.pay.enums.PayWayEnum;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.client.BizPlaceClient;
import com.quanyan.place.component.MerchantClientPayType;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.TbBizPlaceOrderExample.Criteria;
import com.quanyan.place.entity.apireq.ReqBillingInfo;
import com.quanyan.place.entity.apireq.ReqOrderHistory;
import com.quanyan.place.entity.apireq.ReqOrderOperate;
import com.quanyan.place.entity.apireq.ReqPlaceGoodsVo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderDetailVo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderListVo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderSearchVo;
import com.quanyan.place.entity.apireq.ReqPlaceScanOrderSearchVo;
import com.quanyan.place.entity.apireq.ReqRevenueVo;
import com.quanyan.place.entity.apireq.ReqScanPay;
import com.quanyan.place.entity.apireq.ReqShoppingCart;
import com.quanyan.place.entity.apireq.ReqTicketSale;
import com.quanyan.place.entity.apiresp.RespMember;
import com.quanyan.place.entity.apiresp.RespOrderMemberCard;
import com.quanyan.place.entity.apiresp.RespPlaceGoodsInfo;
import com.quanyan.place.entity.apiresp.RespPlaceOrderDetails;
import com.quanyan.place.entity.apiresp.RespPlaceOrderDiscountItem;
import com.quanyan.place.entity.apiresp.RespPlaceOrderMessage;
import com.quanyan.place.entity.apiresp.RespPlacePrintInfo;
import com.quanyan.place.entity.apiresp.RespPlaceUtilizationVo;
import com.quanyan.place.entity.apiresp.RespProductUnitInfo;
import com.quanyan.place.entity.apiresp.RespRevenueVo;
import com.quanyan.place.entity.apiresp.RespTicketSaleInfo;
import com.quanyan.place.entity.vo.DictPlaceDataVo;
import com.quanyan.place.entity.vo.PlacePrintVo;
import com.quanyan.place.entity.vo.PlaceScanOrderPayVo;
import com.quanyan.place.entity.vo.RespPlaceRevenueStats;
import com.quanyan.place.entity.vo.UnitSalePlan;
import com.quanyan.place.enums.PayTypeEnum;
import com.quanyan.place.enums.PlaceErrorCodeEnum;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.*;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sms.SmsApi;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_BASE;
import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;

/**
 * Created by Administrator on 2016/6/2. 场地预定后台管理
 */
@Service
public class PlaceOrderServiceImpl  implements PlaceOrderService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	BizPlaceClient bizPlaceClient;

	@Autowired
	TbStadiumSellHistoryMapper tbStadiumSellHistoryMapper;

	@Autowired
	DictMapper dictMapper;

	@Autowired
	TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;

	@Autowired
	TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

	@Autowired
	TbAdminUserMapper tbAdminUserMapper;

	@Autowired
	TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

	@Autowired
	FinanceCommonManagerMapper financeCommonManagerMapper;

	@Autowired
	TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

	@Autowired
	TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;

	@Autowired
	TbBizPlaceUnitMapper tbBizPlaceUnitMapper;

	@Autowired
	TbBizPlaceUnitTimeMapper tbBizPlaceUnitTimeMapper;

	@Autowired
	TbBizPlaceMapper tbBizPlaceMapper;

	@Autowired
	IBaseService iBaseService;

	@Autowired
	TbBizPlaceRuleMapper tbBizPlaceRuleMapper;

	@Autowired
	UserServiceFacade userServiceFacade;

	@Autowired
	TbBizPlacePrivateOrderMapper tbBizPlacePrivateOrderMapper;

	@Autowired
	TbBizPlaceGoodsMapper tbBizPlaceGoodsMapper;

	@Autowired
	TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;

	@Autowired
	TbSupplierMapper supplierMapper;

	@Autowired
    TbBizPlaceMemberCardTypeTicketMapper tbBizPlaceMemberCardTypeTicketMapper;

	@Value("${notify.url.payUrl}")
	private String payUrl;

	@Value("${notify.url.refundUrl}")
	private String refundUrl;

	@Value("${notify.url.closeOrderUrl}")
	private String closeOrderUrl;

	@Value("${notify.url.payConfirmUrl}")
	private String payConfirmUrl;

	@Autowired
	BaseService baseService;

	@Autowired
	OrderPayService orderPayService;

	@Autowired
	PlaceOrderCallbackService placeOrderCallbackService;

	@Autowired
	TbBizPlaceOrderHistoryMapper tbBizPlaceOrderHistoryMapper;

	@Autowired
	PlaceOrderUtilService placeOrderUtilService;
    @Autowired
    PosUnionPayMapper posUnionPayMapper;

    @Autowired
    TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;

	@Autowired
	private PlaceMemberService placeMemberService;

	@Autowired
	PlaceBaseService placeBaseService;

	@Autowired
	com.quanyan.place.biz.SmsService  placeSmsService;

	@Autowired
	PlaceUnitSalePlanMapper placeUnitSalePlanMapper;

	@Autowired
	TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;

	@Autowired
	TbBizPlaceOrderDiscountItemMapper tbBizPlaceOrderDiscountItemMapper;
	@Autowired
	PlaceOrderAdminMapper placeOrderAdminMapper;
	@Autowired
	TbPlaceTicketStatisticsMapper tbPlaceTicketStatisticsMapper;
	@Autowired
	TbBusinessLogService tbBusinessLogService;
	@Autowired
	PlaceTicketService placeTicketService;
	@Autowired
	PlaceGoodsService placeGoodsService;
	@Autowired
	PlaceInnerService placeInnerService;
	@Autowired
	VPlaceGoodsMapper vPlaceGoodsMapper;
	/**
	 * 查看订单详情
	 * 
	 * @param //rePlaceOrderDetailVo
	 * @return
	 */
	/*
	 * @Override public RespBizPlaceOrderInfo
	 * getProuductUnitInfo(ReqPlaceOrderDetailVo rePlaceOrderDetailVo) {
	 * APIResponse<RespBizPlaceOrderInfo> respPlaceOrderInfo =
	 * bizPlaceClient.placeOrderDetail(rePlaceOrderDetailVo); return
	 * respPlaceOrderInfo.getData(); }
	 */

	public TbStadiumSellHistoryExample setTbStadiumSellHistoryValue(
			ReqPlaceScanOrderSearchVo reqPlaceScanOrderSearchVo) {
		TbStadiumSellHistoryExample tbStadiumSellHistoryExample = new TbStadiumSellHistoryExample();
		TbStadiumSellHistoryExample.Criteria tbBizPlaceOrderExampleCriteria = tbStadiumSellHistoryExample
				.createCriteria();

		// 开始时间
		if (!StringUtils.isEmpty(reqPlaceScanOrderSearchVo.getStartTime())) {
			tbBizPlaceOrderExampleCriteria.andCreateTimeGreaterThanOrEqualTo(
					DateTimeUtils.strToDate(reqPlaceScanOrderSearchVo.getStartTime()));
		}
		// 结束时间
		if (!StringUtils.isEmpty(reqPlaceScanOrderSearchVo.getEndTime())) {
			tbBizPlaceOrderExampleCriteria
					.andCreateTimeLessThanOrEqualTo(DateTimeUtils.strToDate(reqPlaceScanOrderSearchVo.getEndTime()));
		}

		// 支付状态
		if (null != reqPlaceScanOrderSearchVo.getPay_status()) {
			tbBizPlaceOrderExampleCriteria.andPayStateEqualTo(reqPlaceScanOrderSearchVo.getPay_status());
		}

		// 姓名
		if (!StringUtils.isEmpty(reqPlaceScanOrderSearchVo.getUsrName())) {
			tbBizPlaceOrderExampleCriteria.andContactNameLike("%" + reqPlaceScanOrderSearchVo.getUsrName() + "%");
		}

		// 电话号码
		if (!StringUtils.isEmpty(reqPlaceScanOrderSearchVo.getMobile())) {
			tbBizPlaceOrderExampleCriteria.andContactMobileLike("%" + reqPlaceScanOrderSearchVo.getMobile() + "%");
		}
		// 场馆名字
		if (!StringUtils.isEmpty(reqPlaceScanOrderSearchVo.getPlaceName())) {
			tbBizPlaceOrderExampleCriteria.andPlaceNameLike("%" + reqPlaceScanOrderSearchVo.getPlaceName() + "%");
		}
		// 备注
		if (!StringUtils.isEmpty(reqPlaceScanOrderSearchVo.getRemark())) {
			tbBizPlaceOrderExampleCriteria.andRemarkLike("%" + reqPlaceScanOrderSearchVo.getRemark() + "%");
		}
		tbStadiumSellHistoryExample.setOrderByClause("create_time desc");
		return tbStadiumSellHistoryExample;
	}

	/**
	 * 订单列表（新）
	 * 
	 * @param reqPlaceOrderSearchVo
	 * @return
	 */
	@Override
	public PageObj<List<RespPlaceOrderMessage>> getPlaceOrderMessageList(ReqPlaceOrderSearchVo reqPlaceOrderSearchVo) {
		Integer pageSize = reqPlaceOrderSearchVo.getPageSize();
		Integer pageNum = reqPlaceOrderSearchVo.getPageNum();
		if (reqPlaceOrderSearchVo.getPlaceName() != null) {
			reqPlaceOrderSearchVo.setPlaceName(reqPlaceOrderSearchVo.getPlaceName().trim());
		}
		if (null == pageNum) {
			pageNum = 0;
		}
		if (null == pageSize) {
			pageSize = Constants.DEFAULT_PAGE_SIZE;
		}
		Byte searchScope = Constants.BYTE_ONE; // 搜索范围-》默认：指定场馆
		Byte payStatus = reqPlaceOrderSearchVo.getPay_status();
		List<Byte> payStatusTemp = new ArrayList<>();
		// 根据getFlag == 1为默认查询营收统计列表，否则都是按支付状态条件查询
		if (null != reqPlaceOrderSearchVo.getGetFlag() && reqPlaceOrderSearchVo.getGetFlag().equals(1)) {
			if (null != payStatus) {
				payStatusTemp.add(payStatus);
			} else {
				payStatusTemp.add((byte) 2);// 已支付
				payStatusTemp.add((byte) 3);// 已付款
			}
			reqPlaceOrderSearchVo.setPayStatus(payStatusTemp);
		} else {
			if (null != payStatus) {
				payStatusTemp.add(payStatus);
				reqPlaceOrderSearchVo.setPayStatus(payStatusTemp);
			}
		}
		
	

		// 根据前端传递条件,没有placeId,或有cityId，或包含 场馆编号，场馆名称信息 add by yangyun
		if (null == reqPlaceOrderSearchVo.getPlaceId() ||
				null != reqPlaceOrderSearchVo.getCityId() ||
				StringUtils.isNotEmpty(reqPlaceOrderSearchVo.getPlaceCode()) ||
				StringUtils.isNotEmpty(reqPlaceOrderSearchVo.getPlaceName())){
			// 搜索范围设定为-》全部场馆
			searchScope = Constants.BYTE_TWO;
		}
		reqPlaceOrderSearchVo.setSearchScope(searchScope);
		List<Byte> sourceType = new ArrayList<>();

            //1:APP,2:微信公众号,3:商家端
        /*if (null != reqPlaceOrderSearchVo.getChannel()){
            if (reqPlaceOrderSearchVo.getChannel().equals(1) ){
                sourceType.add((byte)1);
                sourceType.add((byte)3);
                sourceType.add((byte)4);
            }else if (reqPlaceOrderSearchVo.getChannel().equals(3)){
                sourceType.add((byte)2);
                if (reqPlaceOrderSearchVo.getPayType() != null){
                    reqPlaceOrderSearchVo.setAdminPayType(reqPlaceOrderSearchVo.getPayType().byteValue());
                }
                reqPlaceOrderSearchVo.setPayType(null);
            }else if ( reqPlaceOrderSearchVo.getChannel().equals(2)){
                sourceType.add((byte)1);
                sourceType.add((byte)3);
                sourceType.add((byte) 4);
               // reqPlaceOrderSearchVo.setPayType(3);//微信公众号支付
              //  reqPlaceOrderSearchVo.setPayType(7);//鸟蛋
               // reqPlaceOrderSearchVo.setPayType(11);//优惠券
            }
            reqPlaceOrderSearchVo.setSourceType(sourceType);
        }*/
		
		
		int total = tbBizPlaceOrderManagerMapper.getPlaceOrderMessageCount(reqPlaceOrderSearchVo);
		reqPlaceOrderSearchVo.setPage(new Page(pageNum * pageSize, pageSize, total));
		List<RespPlaceOrderMessage> placeOrderMessages = tbBizPlaceOrderManagerMapper
				.getPlaceOrderMessageList(reqPlaceOrderSearchVo);
		List<RespPlaceOrderMessage> tempPlaceOrderMessages = getRespPlaceOrderMessage(placeOrderMessages);
		PageObj<List<RespPlaceOrderMessage>> result = PageObj.create(total, pageNum, pageSize, tempPlaceOrderMessages);
		return result;
	}

    /**
     * 不分页导出（新）
     * @param reqPlaceOrderSearchVo
     * @return
     */
    @Override
    public List<RespPlaceOrderMessage> getPlaceOrderMessageListExport(ReqPlaceOrderSearchVo reqPlaceOrderSearchVo) {
        Byte payStatus = reqPlaceOrderSearchVo.getPay_status();
        List<Byte> payStatusTemp = new ArrayList<>();
        //根据getFlag == 1为默认查询营收统计列表，否则都是按支付状态条件查询
        if (null != reqPlaceOrderSearchVo.getGetFlag() && reqPlaceOrderSearchVo.getGetFlag().equals(1)){
            if (null != payStatus){
                payStatusTemp.add(payStatus);
            }else{
                payStatusTemp.add((byte)2);//已支付
                payStatusTemp.add((byte)3);//已付款
            }
            reqPlaceOrderSearchVo.setPayStatus(payStatusTemp);
        }
        
       /* List<Byte> sourceType = new ArrayList<>();
        //1:APP,2:微信公众号,3:商家端
        if (null != reqPlaceOrderSearchVo.getChannel()){
            if (reqPlaceOrderSearchVo.getChannel().equals(1) ){
                sourceType.add((byte)1);
                sourceType.add((byte)3);
                sourceType.add((byte)4);
            }else if (reqPlaceOrderSearchVo.getChannel().equals(3)){
                sourceType.add((byte)2);
                if (reqPlaceOrderSearchVo.getPayType() != null){
                    reqPlaceOrderSearchVo.setAdminPayType(reqPlaceOrderSearchVo.getPayType().byteValue());
                }
                reqPlaceOrderSearchVo.setPayType(null);
            }else if ( reqPlaceOrderSearchVo.getChannel().equals(2)){
                sourceType.add((byte)1);
                sourceType.add((byte)3);
                sourceType.add((byte) 4);
                // reqPlaceOrderSearchVo.setPayType(3);//微信公众号支付
                //  reqPlaceOrderSearchVo.setPayType(7);//鸟蛋
                // reqPlaceOrderSearchVo.setPayType(11);//优惠券
            }
            reqPlaceOrderSearchVo.setSourceType(sourceType);
        }*/
        
        List<RespPlaceOrderMessage> placeOrderMessages = tbBizPlaceOrderManagerMapper.getPlaceOrderMessageList(reqPlaceOrderSearchVo);
        List<RespPlaceOrderMessage> tempPlaceOrderMessages = getRespPlaceOrderMessage(placeOrderMessages);
        return tempPlaceOrderMessages;
    }


    /**
     * 后台扫描支付订单管理列表
	 * 
     * @param reqPlaceScanOrderSearchVo
     * @return
     */
    @Override
	public PageObj<List<TbStadiumSellHistory>> queryPlaceScanOrderList(
			ReqPlaceScanOrderSearchVo reqPlaceScanOrderSearchVo) {
		Integer pageSize = reqPlaceScanOrderSearchVo.getPageSize();
		Integer pageNum = reqPlaceScanOrderSearchVo.getPageNum();
		if (null == pageNum) {
			pageNum = 0;
		}
		if (null == pageSize) {
			pageSize = Constants.DEFAULT_PAGE_SIZE;
		}
		TbStadiumSellHistoryExample tbStadiumSellHistoryExample = setTbStadiumSellHistoryValue(
				reqPlaceScanOrderSearchVo);
		int total = tbStadiumSellHistoryMapper.countByExample(tbStadiumSellHistoryExample);
		tbStadiumSellHistoryExample.setPage(new Page(pageNum * pageSize, pageSize, total));
		List<TbStadiumSellHistory> respPlaceOrderInfoVosList = tbStadiumSellHistoryMapper
				.selectByExample(tbStadiumSellHistoryExample);
		PageObj<List<TbStadiumSellHistory>> result = PageObj.create(total, pageNum, pageSize,
				respPlaceOrderInfoVosList);
		return result;
	}

	private List<TbBizPlaceOrder> getPlaceOrder(Integer parentId) {
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
		tbBizPlaceOrderExampleCriteria.andParentIdEqualTo(parentId);
		List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		return selectByExample;
	}

    /**
     * 次卡 单价
     * @param record
     * @return
     */
    private RespPlaceOrderMessage ciCardAmount(RespPlaceOrderMessage record){
            if (null != record){
                if (!StringUtils.isEmpty(record.getPayType()) && record.getPayType().equals("10")){
                    Map<String, Object> params = new HashMap<>();
                    params.put("placeId",record.getPlaceId());
					String memberCardNo = record.getSubjectCode();
					if (StringUtils.isEmpty(record.getSubjectCode())){
						String orderNo = record.getPlaceOrderId();
						TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
						TbBizPlaceMemberOpHistoryExample.Criteria tbBizPlaceMemberOpHistoryCriteria = tbBizPlaceMemberOpHistoryExample.createCriteria();
						tbBizPlaceMemberOpHistoryCriteria.andOrderNoEqualTo(orderNo);
						List<TbBizPlaceMemberOpHistory> recordList  = tbBizPlaceMemberOpHistoryMapper.selectByExample(tbBizPlaceMemberOpHistoryExample);
						if (null != recordList && recordList.size() > 0 ){
							memberCardNo = recordList.get(0).getInnerCardNo();
						}
					}
					if (StringUtils.isEmpty(memberCardNo)){
						return record;
					} else {
						params.put("memberCardNo",memberCardNo);
					}
					List<TbBizPlaceMemberCardTypeInitAmount> memberCardTypeList = posUnionPayMapper
                            .selectCardTypeInitAmoutByPK(params);
					TbBizPlaceMemberCardTypeInitAmount memberCardType = null;
					if (null != memberCardTypeList && memberCardTypeList.size() > 0){
						memberCardType = memberCardTypeList.get(0);
					}
                    if (memberCardType != null) {
                        if(memberCardType.getCardType() == 4){
                            BigDecimal bigDecimal = (memberCardType.getInitAmount()
                                    .divide(new BigDecimal(memberCardType.getFrequency()), 2, BigDecimal.ROUND_HALF_UP));// 计算次卡单价
                            bigDecimal = bigDecimal.multiply(new BigDecimal(record.getTicketCount())).setScale(2, BigDecimal.ROUND_HALF_UP);
                            record.setDiscountAmount(bigDecimal);
                        }
                    }
                }
            }

        return record;

    }
	/**
	 * 封装订单及订单支付方式对象（新）
	 * 
	 * @param records
	 * @return
	 */
	public List<RespPlaceOrderMessage> getRespPlaceOrderMessage(List<RespPlaceOrderMessage> records) {

		for (RespPlaceOrderMessage record : records) {
            record.setSalesDate(record.getConsumeTime());
            /*int channel = record.getChannel().intValue();
            if (channel != 0 || channel == 1 || channel == 2 || channel == 3 || channel == 5){
                // 优惠后金额
                BigDecimal disCountAmount = getDiscountAmount(record);
                if (disCountAmount == null){
                    record.setDiscountAmount(null != disCountAmount ? disCountAmount : new BigDecimal(0.00));
                }else {
                    record.setDiscountAmount(disCountAmount);
                }

            }else{
                // 预订金额
                BigDecimal  disCountAmount = getDiscountAmountByBook(record);
                record.setDiscountAmount(null != disCountAmount ? disCountAmount : new BigDecimal(0.00));

            }*/
            //add 订单管理是否更改支付方式与金额
            String orderNo=record.getOrderNo();
            if(StringUtil.isNotBlank(orderNo)){
            	record.setIsChangePay(0);
            }else{
            	record.setIsChangePay(1);
            }

			BigDecimal disCountAmount = getDiscountAmount(record);
			if (disCountAmount == null &&
					null != record.getOrderStatus() &&
					PlaceConstants.ORDER_PREPAY_STATUS == record.getOrderStatus()){
				// 预订金额
				disCountAmount = getDiscountAmountByBook(record);
			}
			record.setDiscountAmount(null != disCountAmount ? disCountAmount : new BigDecimal(0.00));


            // 优惠金额
			if (null != record.getDebit() && null != record.getDiscountAmount()
					&& record.getDebit().compareTo(record.getDiscountAmount()) > 0) {
				record.setTakeOutAmount(record.getDebit().subtract(record.getDiscountAmount()));
			} else {
				record.setTakeOutAmount(BigDecimal.ZERO);
			}



            if (!StringUtils.isEmpty(record.getPayType()) && record.getPayType().equals("10")){
                record = ciCardAmount(record);
            }
			record.setOrderStatusChangeDate(record.getOrderStatusChangeDate());
			// 支付明细
			// List<TbBizPlacePayItem> payItemList =
			// getPayItem(record.getPlaceOrderId(),null);
			// 根据uid查询开单人
			Integer createUid = record.getCreateUid();
			if (null != createUid) {
				TbAdminUser tbAdminUser = tbAdminUserMapper.selectByPrimaryKey(createUid);
				if (tbAdminUser != null) {
					record.setCreateUserName(tbAdminUser.getTrueName());
				}
			}


			// 消费时间
			List<TbBizPlaceOrderItem> tbBizPlaceOrderItem = getTbBizPlaceOrderItem(record.getPlaceOrderId());

			/*if (null != tbBizPlaceOrderItem && tbBizPlaceOrderItem.size() > 0) {
                Map<String,Object> maps = new HashMap<>();
				for (TbBizPlaceOrderItem orderItem : tbBizPlaceOrderItem) {
					if (useType.equals((byte) 2)) {// TODO 2门票
						record.setSalesDate(orderItem.getConsumeTime());
					} else if (useType.equals((byte) 4)) {// TODO 4商品
						record.setSalesDate(record.getOrderTime());

					} else if (useType.equals((byte) 0) || useType.equals((byte) 3)) {
						RespProductUnitInfo respProductUnitInfo = getProductUnitInfo(orderItem.getUnitSalePlanId());
						record.setSalesDate(respProductUnitInfo.getDate());

					} else if (useType.equals((byte) 1)) {// TODO 包场
						RespProductUnitInfo respProductUnitInfo = getProductUnitInfoBySaleId(orderItem.getSaleId());
						record.setSalesDate(respProductUnitInfo.getDate());
					}
				}
			}*/
			  
			  BigDecimal totalsPrices=new BigDecimal(0.00);
		      TreeSet<Byte> useTypes=new TreeSet<>();
		     if(null != tbBizPlaceOrderItem && tbBizPlaceOrderItem.size() > 0) {
		    	 /**订单金额**/
				
		    	  for (TbBizPlaceOrderItem orderItem : tbBizPlaceOrderItem) {
		    		  if(orderItem.getUseType().equals(Byte.parseByte("3"))){//app开单转为开单
		    			  orderItem.setUseType((byte)0);
		    		  }
		    		  useTypes.add(orderItem.getUseType());
		    		  totalsPrices=totalsPrices.add(this.handleDecimalNull(orderItem.getOriginPrice()).multiply(new BigDecimal(orderItem.getTotalGoodsCount())));
		    	  }
                  Byte[] array=new Byte[useTypes.size()];
                  record.setUseTypes(useTypes.toArray(array));
                  
				
				  Map<String,Object> map = new HashMap<>();
				  map.put("placeOrderId",record.getPlaceOrderId());
				
		            if (totalsPrices.compareTo(new BigDecimal(0))!=0){
		                record.setDebit(totalsPrices);
		            }else{
		                /**为兼容老版本数据**/
		                BigDecimal oldTotalsPrices = new BigDecimal(0.00);
		                List<String> goodId = new ArrayList<>();
		                if (null != tbBizPlaceOrderItem && tbBizPlaceOrderItem.size() > 0) {
		                    for (TbBizPlaceOrderItem orderItem : tbBizPlaceOrderItem) {
		                        /**针对：门票（2） 商品（4）**/
		                        if (orderItem.getUseType().equals((byte) 2) || orderItem.getUseType().equals((byte) 4)){
									goodId.clear();
		                            goodId.add(String.valueOf(orderItem.getUnitSalePlanId()));
		                            map.put("goodId",goodId);
		                          
		                            
		                            for(int i=0;i<record.getUseTypes().length;i++){
		                            	BigDecimal ticketPrice=new BigDecimal(0.00);
		        			            map.put("useType",record.getUseTypes()[i]);
		        			            ticketPrice =ticketPrice.add(this.handleDecimalNull(tbBizPlaceOrderManagerMapper.oldOrderTotalsPrices(map)));
		        			           /**单个商品价格（原价）**/
		                                oldTotalsPrices = oldTotalsPrices.add(ticketPrice.multiply(new BigDecimal(orderItem.getTicketCount())));
		        			             map.remove("useType");
		        					}
		                               
		                        }else{
		                            goodId.add(orderItem.getSaleId());
		                            map.put("goodId",goodId);
		                        }
		                    }
		                    
		                    /**开单包场直接sum销售计划原价总和**/
		                   for(int i=0;i<record.getUseTypes().length;i++){
		                	   if (record.getUseTypes()[i].equals((byte) 0) || record.getUseTypes()[i].equals((byte) 3) ||  record.getUseTypes()[i].equals((byte) 1)) {
		                		    map.put("useType",record.getUseTypes()[i]);
		       			            oldTotalsPrices =oldTotalsPrices.add(this.handleDecimalNull(tbBizPlaceOrderManagerMapper.oldOrderTotalsPrices(map)));
		       			            map.remove("useType");
			                    }
       			          
       					}
		               
		                }
		                record.setDebit(oldTotalsPrices);
		            }
		      }
		     
		
		     /*String adminPay = record.getAdminPay();
		     if (!StringUtils.isEmpty(adminPay)) {
					String[] adminPays = adminPay.split(",");
					List<Integer> temp = new ArrayList<>();
					for (int i = 0; i < adminPays.length; i++) {
						temp.add(Integer.valueOf(adminPays[i]));
					}
	                record.setAdminPayTypes(temp);
	               
	            }*/
		     
		     TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
				TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
				tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(record.getPlaceOrderId());
				List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper
						.selectByExample(tbBizPlacePayItemExample);
				if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlacePayItemList)){
					 TreeSet<Integer> adminPayTypes=new TreeSet<>();
					 for(TbBizPlacePayItem payItem:tbBizPlacePayItemList){
						 adminPayTypes.add(payItem.getAdminPayType());
					 }
					  Integer[] array=new Integer[adminPayTypes.size()];
	                  record.setAdminPayTypes(adminPayTypes.toArray(array));
				}
		    
        }
        return records;
    }


	/**
	 * 订单预订实付金额
	 * 
	 * @param placeOrder
	 * @return
	 */
	public BigDecimal getDiscountAmountByBook(RespPlaceOrderMessage placeOrder) {
		Map<String, Object> map = new HashMap();
		List<String> listPlaceOrderId = new ArrayList<>();

		listPlaceOrderId.add(placeOrder.getPlaceOrderId());
		map.put("placeOrderId", listPlaceOrderId);

		return financeCommonManagerMapper.getDiscountAmountByBook(map);
	}

	/**
	 * 订单实付金额
	 * 
	 * @param placeOrder
	 * @return
	 */
	public BigDecimal getDiscountAmount(RespPlaceOrderMessage placeOrder) {
		Map<String, Object> map = new HashMap();
		List<String> listPlaceOrderId = new ArrayList<>();

		/*
		 * if (useType.equals((byte)1)){ List<TbBizPlaceOrder> placeOrder =
		 * getPlaceOrder(record.getParentId()); for (TbBizPlaceOrder
		 * tbBizPlaceOrder : placeOrder) {
		 * listPlaceOrderId.add(tbBizPlaceOrder.getPlaceOrderId()); } }else{
		 * listPlaceOrderId.add(record.getPlaceOrderId()); }
		 */
		listPlaceOrderId.add(placeOrder.getPlaceOrderId());
		map.put("placeOrderId", listPlaceOrderId);
		/*
		 * List<Byte> orderStatus = new ArrayList<>();
		 * orderStatus.add(placeOrder.getOrderStatus()); map.put("orderStatus",
		 * orderStatus);
		 */
		return financeCommonManagerMapper.getDiscountAmount(map);
	}

	/**
	 * 选择条件
	 * 
	 * @return
	 */
	public Map<String, List<DictPlaceDataVo>> getOrderCondition(Integer businessMode) {
		DictExample dictExample = new DictExample();
		DictExample.Criteria dictExampleCriteria = dictExample.createCriteria();
		List<String> list = new ArrayList<>();
		list.add("22");
		list.add("23");
		list.add("24");
        list.add("25");//APP
        list.add("200");//微信公众号
        list.add("201");//H5支付方式
        list.add("26");//商家端支付方式
        list.add("202");//小程序支付方式

        list.add("27");//销售渠道
        //list.add("28");//微信公众号
        list.add("30");//后台订单类型
        dictExampleCriteria.andTagGroupIn(list);
        List<Dict> dict = dictMapper.selectByExample(dictExample);
        Map<String,List<DictPlaceDataVo>> map = new HashMap<>();
       if (dict != null && dict.size()>0){
           map = getDictKeyAndValue(dict,businessMode);
       }
      return map;
    }

	/**
	 * 筛选条件参数过滤
	 * 
	 * @param dict
	 * @return
	 */
	public Map<String, List<DictPlaceDataVo>> getDictKeyAndValue(List<Dict> dict,Integer businessMode) {
		List<DictPlaceDataVo> cagetory_type = new ArrayList<>();
		List<DictPlaceDataVo> order_status = new ArrayList<>();
		List<DictPlaceDataVo> pay_status = new ArrayList<>();

        /**销售渠道**/
        List<DictPlaceDataVo> sale_way = new ArrayList<>();
        /**App支付方式**/
        List<DictPlaceDataVo> appPayType = new ArrayList<>();
        /**微信公众号支付**/
        List<DictPlaceDataVo> wxPayType = new ArrayList<>();
        /***H5支付方式**/
        List<DictPlaceDataVo> h5PayType = new ArrayList<>();
        /***商家端支付方式**/
        List<DictPlaceDataVo> adminPayType = new ArrayList<>();
        /**小程序支付方式**/
        List<DictPlaceDataVo> weAppPayType = new ArrayList<>();
        /**订单管理支付方式**/
        List<DictPlaceDataVo> payType = new LinkedList<>();
        
        DictPlaceDataVo dictPlaceDataVo4 = new DictPlaceDataVo();
        dictPlaceDataVo4.setData_key("10");
		dictPlaceDataVo4.setData_value("会员卡"); 
        payType.add(dictPlaceDataVo4); 
        DictPlaceDataVo dictPlaceDataVo2 = new DictPlaceDataVo();
        dictPlaceDataVo2.setData_key("2");
		dictPlaceDataVo2.setData_value("微信"); 
        payType.add(dictPlaceDataVo2); 
        DictPlaceDataVo dictPlaceDataVo1 = new DictPlaceDataVo();
        dictPlaceDataVo1.setData_key("1");
		dictPlaceDataVo1.setData_value("支付宝"); 
        payType.add(dictPlaceDataVo1);  
        DictPlaceDataVo dictPlaceDataVo6 = new DictPlaceDataVo();
        dictPlaceDataVo6.setData_key("20");
		dictPlaceDataVo6.setData_value("现金"); 
        payType.add(dictPlaceDataVo6); 
        DictPlaceDataVo dictPlaceDataVo11 = new DictPlaceDataVo();
        dictPlaceDataVo11.setData_key("29");
		dictPlaceDataVo11.setData_value("对公转账"); 
        payType.add(dictPlaceDataVo11); 
       /* DictPlaceDataVo dictPlaceDataVo17 = new DictPlaceDataVo();
        dictPlaceDataVo17.setData_key("37");
		dictPlaceDataVo17.setData_value("赠送"); 
        payType.add(dictPlaceDataVo17);*/
  
        
        
        if(businessMode==null || businessMode==1){
         DictPlaceDataVo dictPlaceDataVo7 = new DictPlaceDataVo();
             dictPlaceDataVo7.setData_key("23");
       	    dictPlaceDataVo7.setData_value("POS银行卡"); 
            payType.add(dictPlaceDataVo7);  
       
         DictPlaceDataVo dictPlaceDataVo3 = new DictPlaceDataVo();
        dictPlaceDataVo3.setData_key("7");
		dictPlaceDataVo3.setData_value("鸟蛋"); 
        payType.add(dictPlaceDataVo3);  
        
        DictPlaceDataVo dictPlaceDataVo5 = new DictPlaceDataVo();
        dictPlaceDataVo5.setData_key("11");
		dictPlaceDataVo5.setData_value("优惠券"); 
        payType.add(dictPlaceDataVo5);  
       
     
        DictPlaceDataVo dictPlaceDataVo8 = new DictPlaceDataVo();
        dictPlaceDataVo8.setData_key("24");
		dictPlaceDataVo8.setData_value("与场馆老板结算"); 
        payType.add(dictPlaceDataVo8); 
        DictPlaceDataVo dictPlaceDataVo9 = new DictPlaceDataVo();
        dictPlaceDataVo9.setData_key("25");
		dictPlaceDataVo9.setData_value("与外部公司结算"); 
        payType.add(dictPlaceDataVo9); 
        DictPlaceDataVo dictPlaceDataVo10 = new DictPlaceDataVo();
        dictPlaceDataVo10.setData_key("26");
		dictPlaceDataVo10.setData_value("与公司内部核算"); 
        payType.add(dictPlaceDataVo10); 
        }
        
        if(businessMode==null || businessMode==2){
        	 DictPlaceDataVo dictPlaceDataVo15 = new DictPlaceDataVo();
             dictPlaceDataVo15.setData_key("33");
     		dictPlaceDataVo15.setData_value("微信(场馆自有)"); 
             payType.add(dictPlaceDataVo15); 
             
        	DictPlaceDataVo dictPlaceDataVo14 = new DictPlaceDataVo();
            dictPlaceDataVo14.setData_key("32");
    		dictPlaceDataVo14.setData_value("支付宝(场馆自有)"); 
            payType.add(dictPlaceDataVo14); 
           
            DictPlaceDataVo dictPlaceDataVo16 = new DictPlaceDataVo();
            dictPlaceDataVo16.setData_key("34");
    		dictPlaceDataVo16.setData_value("POS银行卡(场馆自有)"); 
            payType.add(dictPlaceDataVo16); 
            
            DictPlaceDataVo dictPlaceDataVo12 = new DictPlaceDataVo();
            dictPlaceDataVo12.setData_key("30");
    		dictPlaceDataVo12.setData_value("挂账"); 
            payType.add(dictPlaceDataVo12); 
            
            DictPlaceDataVo dictPlaceDataVo13 = new DictPlaceDataVo();
            dictPlaceDataVo13.setData_key("31");
    		dictPlaceDataVo13.setData_value("团购券"); 
            payType.add(dictPlaceDataVo13); 
        }
       
        
       
      
        
		List<DictPlaceDataVo> use_type = new ArrayList<>();
		Map<String, List<DictPlaceDataVo>> map = new LinkedHashMap<>();
		for (Dict dict1 : dict) {
			String tagGroup = dict1.getTagGroup();
			if (tagGroup.equals("22")) {
				DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
				dictPlaceDataVo.setData_key(dict1.getDataKey());
				dictPlaceDataVo.setData_value(dict1.getDataValue());
				cagetory_type.add(dictPlaceDataVo);
			}
			if (tagGroup.equals("23")) {
				DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
				dictPlaceDataVo.setData_key(dict1.getDataKey());
				dictPlaceDataVo.setData_value(dict1.getDataValue());
				order_status.add(dictPlaceDataVo);
			}
			if (tagGroup.equals("24")) {
				DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
				dictPlaceDataVo.setData_key(dict1.getDataKey());
				dictPlaceDataVo.setData_value(dict1.getDataValue());
				pay_status.add(dictPlaceDataVo);
			}
            if (tagGroup.equals("25")){ /**APP**/
                DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
                dictPlaceDataVo.setData_key(dict1.getDataKey());
                dictPlaceDataVo.setData_value(dict1.getDataValue());
                appPayType.add(dictPlaceDataVo);
            }

            if (tagGroup.equals("200")){ /**微信公众号**/
                DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
                dictPlaceDataVo.setData_key(dict1.getDataKey());
                dictPlaceDataVo.setData_value(dict1.getDataValue());
                wxPayType.add(dictPlaceDataVo);
            }

            if (tagGroup.equals("201")){ /**H5支付方式**/
                DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
                dictPlaceDataVo.setData_key(dict1.getDataKey());
                dictPlaceDataVo.setData_value(dict1.getDataValue());
                h5PayType.add(dictPlaceDataVo);
            }


            if (tagGroup.equals("26")){ /**商家端支付方式**/
                DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
                dictPlaceDataVo.setData_key(dict1.getDataKey());
                dictPlaceDataVo.setData_value(dict1.getDataValue());
                adminPayType.add(dictPlaceDataVo);
            }

            if (tagGroup.equals("202")){ /**小程序支付方式**/
                DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
                dictPlaceDataVo.setData_key(dict1.getDataKey());
                dictPlaceDataVo.setData_value(dict1.getDataValue());
                weAppPayType.add(dictPlaceDataVo);
            }



            if (tagGroup.equals("27")){
                DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
                dictPlaceDataVo.setData_key(dict1.getDataKey());
                dictPlaceDataVo.setData_value(dict1.getDataValue());
                sale_way.add(dictPlaceDataVo);
            }

            if (tagGroup.equals("30")){
                DictPlaceDataVo dictPlaceDataVo = new DictPlaceDataVo();
                dictPlaceDataVo.setData_key(dict1.getDataKey());
                dictPlaceDataVo.setData_value(dict1.getDataValue());
                use_type.add(dictPlaceDataVo);
            }

            /**运动类型**/
            map.put("cagetory_type",cagetory_type);
            /**订单状态**/
            map.put("order_status",order_status);
            /**支付状态**/
            map.put("pay_status",pay_status);
            /**销售渠道**/
            map.put("sale_way",sale_way);
            /**支付方式**/
            map.put("appPayType",appPayType);
            map.put("wxPayType",wxPayType);
            map.put("h5PayType",h5PayType);
            map.put("adminPayType",adminPayType);
            map.put("weAppPayType",weAppPayType);
           
            
            /**订单类型**/
            map.put("use_type",use_type);
        }
		map.put("payType", payType);
		 
        return  map;
    }

	public List<Integer> getResourceType(Integer flag, ReqRevenueVo reqRevenueVo) {
		// 订单来源线上还是线下
		List<Integer> sourceTypeList = new ArrayList<>();
		if (null != sourceTypeList && sourceTypeList.size() > 0) {
			sourceTypeList.clear();
		}
		// 线上订单 订单来源类型 1：普通订场业务 2：现场支付业务 3：竞拍业务
		if (flag.equals(1)) {
			sourceTypeList.add(1);
			sourceTypeList.add(3);
		} else if (flag.equals(2)) {// 线下订单
			sourceTypeList.add(2);
		}
		return sourceTypeList;
	}

	/**
	 * 获取订单数量及订单金额（线上及线下）
	 * 
	 * @param flag
	 * @param reqRevenueVo
	 * @return
	 */
	private Map<Integer, RespPlaceRevenueStats> getOrderCountAndAmount(Integer flag, ReqRevenueVo reqRevenueVo) {
		Map<Integer, RespPlaceRevenueStats> map = new HashMap<>();
		// 区分线上线下订单数及订单金额
		List<Integer> sourceType = null;
		if (flag == 1) {
			sourceType = getResourceType(flag, reqRevenueVo);
		} else if (flag == 2) {
			sourceType = getResourceType(flag, reqRevenueVo);
		}
		reqRevenueVo.setSourceType(sourceType);
		// 线上订单总数和线下订单总数
		List<RespRevenueVo> orderCountLists = tbBizPlaceOrderManagerMapper.selectOrderCount(reqRevenueVo);
		for (RespRevenueVo orderCountList : orderCountLists) {
			Integer categoryId = orderCountList.getCategoryId();
			RespPlaceRevenueStats revenueStats = new RespPlaceRevenueStats();
			if (!map.containsKey(categoryId)) {
				revenueStats.setCategoryId(categoryId);
				if (flag == 1) {
					revenueStats.setOnLineOrderCount(orderCountList.getOrderCount());
					revenueStats.setOnLineAmount(orderCountList.getOrderAmount());
				}
				if (flag == 2) {
					revenueStats.setOffLineOrderCount(orderCountList.getOrderCount());
					revenueStats.setOffLineAmount(orderCountList.getOrderAmount());
				}
				map.put(categoryId, revenueStats);
			} else {
				RespPlaceRevenueStats placeReventStats = map.get(categoryId);
				placeReventStats.setCategoryId(categoryId);
				if (flag == 1) {
					revenueStats.setOnLineOrderCount(orderCountList.getOrderCount());
					revenueStats.setOnLineAmount(orderCountList.getOrderAmount());
				}
				if (flag == 2) {
					revenueStats.setOffLineOrderCount(orderCountList.getOrderCount());
					revenueStats.setOffLineAmount(orderCountList.getOrderAmount());
				}
				map.put(categoryId, placeReventStats);
			}
		}

		return map;
	}

	public Map<Integer, RespPlaceRevenueStats> getCommonOrderCountAndAmount(ReqRevenueVo reqRevenueVo) {
		// 线上
		Map<Integer, RespPlaceRevenueStats> onLineRevenue = getOrderCountAndAmount(1, reqRevenueVo);
		// 线下
		Map<Integer, RespPlaceRevenueStats> offLineRevenue = getOrderCountAndAmount(2, reqRevenueVo);

		if (!onLineRevenue.isEmpty() && !offLineRevenue.isEmpty()) {
			for (Map.Entry<Integer, RespPlaceRevenueStats> entry : offLineRevenue.entrySet()) {
				Integer key = entry.getKey();
				if (!onLineRevenue.containsKey(key)) {
					onLineRevenue.put(entry.getKey(), entry.getValue());
				} else {
					RespPlaceRevenueStats onLineObj = onLineRevenue.get(key);
					RespPlaceRevenueStats offLineObj = entry.getValue();
					onLineObj.setOffLineOrderCount(offLineObj.getOffLineOrderCount());
					onLineObj.setOffLineAmount(offLineObj.getOffLineAmount());
					onLineRevenue.put(key, onLineObj);
				}
			}
			return onLineRevenue;
		} else if (!onLineRevenue.isEmpty() && offLineRevenue.isEmpty()) {
			return onLineRevenue;
		} else if (onLineRevenue.isEmpty() && !offLineRevenue.isEmpty()) {
			return offLineRevenue;
		}
		return null;
	}

	/**
	 * 获取订单不同支付订单金额（线上及线下）
	 * 
	 * @param flag
	 * @param reqRevenueVo
	 * @return
	 */
	private Map<Integer, RespPlaceRevenueStats> getOrderAmountByPayType(Integer flag, ReqRevenueVo reqRevenueVo) {
		List<Integer> sourceType = null;
		reqRevenueVo.setSourceType(sourceType);
		if (flag == 1) {
			Map<Integer, RespPlaceRevenueStats> map = new HashMap<>();
			sourceType = getResourceType(flag, reqRevenueVo);
			reqRevenueVo.setSourceType(sourceType);
			int[] linePayType = { 1, 2, 10, 11 };
			// 线上订单各种支付方式总额1：支付宝支付 2：微信支付 10 ：会员卡支付 11：优惠券支付
			for (int i = 0; i < linePayType.length; i++) {
				reqRevenueVo.setPayType(Arrays.asList(linePayType[i]));
				List<RespRevenueVo> orderCountLists = tbBizPlaceOrderManagerMapper
						.selectOrderAmountByPayType(reqRevenueVo);
				if (!CollectionUtils.isEmpty(orderCountLists)) {
					for (RespRevenueVo orderCountList : orderCountLists) {
						Integer categoryId = orderCountList.getCategoryId();
						RespPlaceRevenueStats revenueStats = new RespPlaceRevenueStats();
						if (!map.containsKey(categoryId)) {
							revenueStats.setCategoryId(categoryId);
							switch (linePayType[i]) {
							case 1:
								revenueStats.setOnLineAlipayAmount(orderCountList.getAmount());// 1
																								// ：支付宝支付
								break;
							case 2:
								revenueStats.setOnLineWeChatAmount(orderCountList.getAmount());// 2:微信支付
								break;
							case 10:
								revenueStats.setOnLineCardPayAmount(orderCountList.getAmount());// 10:会员卡支付
								break;
							case 11:
								revenueStats.setOnLineCouponAmount(orderCountList.getAmount());// 11:优惠券支付
								break;
							}
							map.put(categoryId, revenueStats);
						} else {
							RespPlaceRevenueStats onLineObj = map.get(categoryId);
							switch (linePayType[i]) {
							case 1:
								onLineObj.setOnLineAlipayAmount(orderCountList.getAmount());// 1
																							// ：支付宝支付
								break;
							case 2:
								onLineObj.setOnLineWeChatAmount(orderCountList.getAmount());// 2:微信支付
								break;
							case 10:
								onLineObj.setOnLineCardPayAmount(orderCountList.getAmount());// 10:会员卡支付
								break;
							case 11:
								onLineObj.setOnLineCouponAmount(orderCountList.getAmount());// 11:优惠券支付
								break;
							}
							map.put(categoryId, onLineObj);
						}

					}
				}

			}
			return map;
		} else if (flag == 2) {
			Map<Integer, RespPlaceRevenueStats> map = new HashMap<>();
			sourceType = getResourceType(flag, reqRevenueVo);
			reqRevenueVo.setSourceType(sourceType);
			// 10:会员卡支付 20:现金 21:微信扫码 22:支付宝扫码 23:银联 24:与场馆老板结算 25:与外部公司结算
			// 26:与总部内部核算
			int[] offLinePayType = { 10, 20, 21, 22, 23, 24, 25, 26 };
			for (int i = 0; i < offLinePayType.length; i++) {
				reqRevenueVo.setPayType(Arrays.asList(offLinePayType[i]));
				List<RespRevenueVo> orderCountLists = tbBizPlaceOrderManagerMapper
						.selectOrderAmountByPayType(reqRevenueVo);
				if (!CollectionUtils.isEmpty(orderCountLists)) {
					for (RespRevenueVo orderCountList : orderCountLists) {
						Integer categoryId = orderCountList.getCategoryId();
						RespPlaceRevenueStats revenueStats = new RespPlaceRevenueStats();
						if (!map.containsKey(categoryId)) {
							revenueStats.setCategoryId(categoryId);
							switch (offLinePayType[i]) {
							case 10:
								revenueStats.setOffLineCardPayAmount(orderCountList.getAmount());// 10
																									// ：会员卡支付
								break;
							case 20:
								revenueStats.setOffLineCashAmount(orderCountList.getAmount());// 20:现金
								break;
							case 21:
								revenueStats.setOffLineWeChatAmount(orderCountList.getAmount());// 21:微信扫码
								break;
							case 22:
								revenueStats.setOffLineAlipayAmount(orderCountList.getAmount());// 22:支付宝扫码
								break;
							case 23:
								revenueStats.setOffLineUnionPayAmount(orderCountList.getAmount());// 23:银联
								break;
							case 24:
								revenueStats.setOffLinePlaceStatAmount(orderCountList.getAmount());// 24:与场馆老板结算
								break;
							case 25:
								revenueStats.setOffLineOtherCompanyAmount(orderCountList.getAmount());// 25:与外部公司结算
								break;
							case 26:
								revenueStats.setOffLineInsideStatAmount(orderCountList.getAmount());// 26:与总部内部核算
								break;
							}
							map.put(categoryId, revenueStats);
						} else {
							RespPlaceRevenueStats onLineObj = map.get(categoryId);
							switch (offLinePayType[i]) {
							case 10:
								onLineObj.setOffLineCardPayAmount(orderCountList.getAmount());// 10
																								// ：会员卡支付
								break;
							case 20:
								onLineObj.setOffLineCashAmount(orderCountList.getAmount());// 20:现金
								break;
							case 21:
								onLineObj.setOffLineWeChatAmount(orderCountList.getAmount());// 21:微信扫码
								break;
							case 22:
								onLineObj.setOffLineAlipayAmount(orderCountList.getAmount());// 22:支付宝扫码
								break;
							case 23:
								onLineObj.setOffLineUnionPayAmount(orderCountList.getAmount());// 23:银联
								break;
							case 24:
								onLineObj.setOffLinePlaceStatAmount(orderCountList.getAmount());// 24:与场馆老板结算
								break;
							case 25:
								onLineObj.setOffLineOtherCompanyAmount(orderCountList.getAmount());// 25:与外部公司结算
								break;
							case 26:
								onLineObj.setOffLineInsideStatAmount(orderCountList.getAmount());// 26:与总部内部核算
								break;
							}
							map.put(categoryId, onLineObj);
						}
					}
				}
			}

			return map;
		}
		return null;
	}

	private Map<Integer, RespPlaceRevenueStats> getCommonAmountByPayType(ReqRevenueVo reqRevenueVo) {
		Map<Integer, RespPlaceRevenueStats> onLineOrderAmountByPayType = getOrderAmountByPayType(1, reqRevenueVo);
		Map<Integer, RespPlaceRevenueStats> offLineOrderAmountByPayType = getOrderAmountByPayType(2, reqRevenueVo);

		if (!onLineOrderAmountByPayType.isEmpty() && !offLineOrderAmountByPayType.isEmpty()) {
			for (Map.Entry<Integer, RespPlaceRevenueStats> entry : offLineOrderAmountByPayType.entrySet()) {
				Integer key = entry.getKey();
				if (!onLineOrderAmountByPayType.containsKey(key)) {
					onLineOrderAmountByPayType.put(entry.getKey(), entry.getValue());
				} else {
					RespPlaceRevenueStats onLineObj = onLineOrderAmountByPayType.get(key);
					RespPlaceRevenueStats offLineObj = entry.getValue();
					onLineObj.setOffLineCardPayAmount(offLineObj.getOffLineCardPayAmount());// 10
																							// ：会员卡支付
					onLineObj.setOffLineCashAmount(offLineObj.getOffLineCashAmount());// 20:现金
					onLineObj.setOffLineWeChatAmount(offLineObj.getOffLineWeChatAmount());// 21:微信扫码
					onLineObj.setOffLineAlipayAmount(offLineObj.getOffLineAlipayAmount());// 22:支付宝扫码
					onLineObj.setOffLineUnionPayAmount(offLineObj.getOffLineUnionPayAmount());// 23:银联
					onLineObj.setOffLinePlaceStatAmount(offLineObj.getOffLinePlaceStatAmount());// 24:与场馆老板结算
					onLineObj.setOffLineOtherCompanyAmount(offLineObj.getOffLineOtherCompanyAmount());// 25:与外部公司结算
					onLineObj.setOffLineInsideStatAmount(offLineObj.getOffLineInsideStatAmount());// 26:与总部内部核算
					onLineOrderAmountByPayType.put(key, onLineObj);
				}
			}
			return onLineOrderAmountByPayType;
		} else if (!onLineOrderAmountByPayType.isEmpty() && offLineOrderAmountByPayType.isEmpty()) {
			return onLineOrderAmountByPayType;
		} else if (onLineOrderAmountByPayType.isEmpty() && !offLineOrderAmountByPayType.isEmpty()) {
			return offLineOrderAmountByPayType;
		}
		return null;
	}

	/**
	 * 营收统计
	 * 
	 * @param reqRevenueVo
	 * @return
	 */
	@Override
	public List<RespPlaceRevenueStats> getPlaceOrderAmountStats(@Param("reqRevenueVo") ReqRevenueVo reqRevenueVo) {
		// 订单数量及金额
		Map<Integer, RespPlaceRevenueStats> orderCountAndAmount = getCommonOrderCountAndAmount(reqRevenueVo);
		Map<Integer, RespPlaceRevenueStats> orderAmountByPayType = getCommonAmountByPayType(reqRevenueVo);

		if (!CollectionUtils.isEmpty(orderCountAndAmount) && !CollectionUtils.isEmpty(orderAmountByPayType)) {
			for (Map.Entry<Integer, RespPlaceRevenueStats> entry : orderAmountByPayType.entrySet()) {
				Integer key = entry.getKey();
				if (!orderCountAndAmount.containsKey(key)) {
					orderCountAndAmount.put(entry.getKey(), entry.getValue());
				} else {
					RespPlaceRevenueStats onLineObj = orderCountAndAmount.get(key);
					RespPlaceRevenueStats offLineObj = entry.getValue();
					// 线下各种支付金额
					onLineObj.setOffLineCardPayAmount(offLineObj.getOffLineCardPayAmount());// 10
																							// ：会员卡支付
					onLineObj.setOffLineCashAmount(offLineObj.getOffLineCashAmount());// 20:现金
					onLineObj.setOffLineWeChatAmount(offLineObj.getOffLineWeChatAmount());// 21:微信扫码
					onLineObj.setOffLineAlipayAmount(offLineObj.getOffLineAlipayAmount());// 22:支付宝扫码
					onLineObj.setOffLineUnionPayAmount(offLineObj.getOffLineUnionPayAmount());// 23:银联
					onLineObj.setOffLinePlaceStatAmount(offLineObj.getOffLinePlaceStatAmount());// 24:与场馆老板结算
					onLineObj.setOffLineOtherCompanyAmount(offLineObj.getOffLineOtherCompanyAmount());// 25:与外部公司结算
					onLineObj.setOffLineInsideStatAmount(offLineObj.getOffLineInsideStatAmount());// 26:与总部内部核算
					// 线上各种支付金额：1：支付宝支付 2：微信支付 10 ：会员卡支付 11：优惠券支付
					onLineObj.setOnLineAlipayAmount(offLineObj.getOnLineAlipayAmount());// 22:支付宝支付
					onLineObj.setOnLineCouponAmount(offLineObj.getOnLineCouponAmount());
					onLineObj.setOnLineWeChatAmount(offLineObj.getOnLineWeChatAmount());// 21:微信支付
					onLineObj.setOnLineCardPayAmount(offLineObj.getOnLineCardPayAmount());// 10
																							// ：会员卡支付
					orderCountAndAmount.put(key, onLineObj);
				}
			}
			logger.info("---->" + JSON.toJSONString(orderCountAndAmount));
			List<RespPlaceRevenueStats> lists = new ArrayList<>(orderCountAndAmount.values());
			return lists;
		} else if (!CollectionUtils.isEmpty(orderCountAndAmount) && CollectionUtils.isEmpty(orderAmountByPayType)) {
			List<RespPlaceRevenueStats> lists = new ArrayList<>(orderCountAndAmount.values());
			return lists;
		} else if (CollectionUtils.isEmpty(orderCountAndAmount) && !CollectionUtils.isEmpty(orderAmountByPayType)) {
			List<RespPlaceRevenueStats> lists = new ArrayList<>(orderAmountByPayType.values());
			return lists;
		}
		return null;
	}

	/**
	 * 场地使用率统计
	 * 
	 * @param reqRevenueVo
	 * @return
	 */
	@Override
	public List<RespPlaceUtilizationVo> getPlaceUtilizationStatistics(
			@Param("reqRevenueVo") ReqRevenueVo reqRevenueVo) {
		Integer placeId = reqRevenueVo.getPlaceId();
		TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
		TbBizPlaceUnitExample.Criteria criteria = tbBizPlaceUnitExample.createCriteria();
		criteria.andPlaceIdEqualTo(placeId);
		// 根据场馆id查询销售单元
		List<TbBizPlaceUnit> tbBizPlaceUnitList = tbBizPlaceUnitMapper.selectByExample(tbBizPlaceUnitExample);
		List<RespPlaceUtilizationVo> placeUtilization = new ArrayList<>();
		if (null != tbBizPlaceUnitList && tbBizPlaceUnitList.size() > 0) {
			for (TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnitList) {
				RespPlaceUtilizationVo resp = new RespPlaceUtilizationVo();
				// 类型
				resp.setCategoryId(tbBizPlaceUnit.getCategoryId());
				// 单元名称
				resp.setPlaceUnitName(tbBizPlaceUnit.getName());
				// 销售单元id
				Integer placeUnitId = tbBizPlaceUnit.getId();
				reqRevenueVo.setPlaceUnitId(placeUnitId);
				// 获取单元空闲小时数
				// resp.setFreeTime(getPlaceUnitFreeTimeAndOccupyTime(1,reqRevenueVo);
				// 获取单元占用小时数
				Integer occupyTime = getPlaceUnitFreeTimeAndOccupyTime(2, reqRevenueVo);
				resp.setOccupyTime(occupyTime);
				// 获取总营业时间
				String startTime = reqRevenueVo.getStartTime();
				String endTime = reqRevenueVo.getEndTime();
				Map<String, Double> map = getOpenHours(placeId, placeUnitId);
				double openTimeCount = 0.0;
				List<String> list = getTimeWeek(startTime, endTime);
				if (!CollectionUtils.isEmpty(map) && !CollectionUtils.isEmpty(list)) {
					for (String s : list) {
						if (map.containsKey(s)) {
							openTimeCount += map.get(s);
						}
					}
				}
				resp.setPlaceOpenTime(openTimeCount);
				// 获取单元空闲小时数
				resp.setFreeTime((int) (openTimeCount - occupyTime));
				// 设置场地单元使用率
				Double aDouble = null;
				if (openTimeCount == 0.0) {
					aDouble = Double.valueOf(occupyTime);
				} else {
					aDouble = occupyTime / openTimeCount * 100;
				}

				BigDecimal bg = new BigDecimal(aDouble).setScale(2, BigDecimal.ROUND_HALF_UP);
				// double f1 = bg.setScale(3,
				// BigDecimal.ROUND_HALF_UP).doubleValue();
				resp.setUtilizationRatio(bg);
				placeUtilization.add(resp);
			}
		}
		return placeUtilization;
	}

	/**
	 * 根据开始时间和结束时间获取区间的星期几
	 * 
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<String> getTimeWeek(String startTime, String endTime) {
		int diffDays = DateTimeUtils.diffDays(DateUtils.strToDate(endTime), DateUtils.strToDate(startTime));
		List<String> list = new ArrayList<>();
		long starts = DateUtils.strToDate(startTime).getTime();
		long ends = DateUtils.strToDate(endTime).getTime();
		for (int i = 0; i <= diffDays; i++) {
			if (starts == ends) {
				String temp = DateUtils.transferLongToDateString(starts);
				list.add(DateUtils.dayForWeeks(temp));
				break;
			} else if (ends > starts) {
				String temp = DateUtils.transferLongToDateString(ends);
				list.add(DateUtils.dayForWeeks(temp));
			}
			ends -= 1000 * 60 * 60 * 24;
		}
		return list;
	}

	/**
	 * 获取营业时间
	 * 
	 * @param placeId
	 * @param placeUnitId
	 * @return
	 */
	public Map<String, Double> getOpenHours(Integer placeId, Integer placeUnitId) {
		TbBizPlaceUnitTimeExample tbBizPlaceUnitTimeExample = new TbBizPlaceUnitTimeExample();
		TbBizPlaceUnitTimeExample.Criteria criteria = tbBizPlaceUnitTimeExample.createCriteria();
		criteria.andPlaceIdEqualTo(placeId);
		criteria.andPlaceUnitIdEqualTo(placeUnitId);
		List<TbBizPlaceUnitTime> list = tbBizPlaceUnitTimeMapper.selectByExample(tbBizPlaceUnitTimeExample);
		Map<String, Double> map = new ConcurrentHashMap<>();
		for (TbBizPlaceUnitTime tbBizPlaceUnitTime : list) {
			if (!map.containsKey(tbBizPlaceUnitTime.getTimeType())) {
				map.put(tbBizPlaceUnitTime.getTimeType(), tbBizPlaceUnitTime.getTimeLength());
			} else {
				double tempValue = map.get(tbBizPlaceUnitTime.getTimeType());
				map.put(tbBizPlaceUnitTime.getTimeType(), tbBizPlaceUnitTime.getTimeLength() + tempValue);
			}

		}
		return map;
	}

	/**
	 * 获取空闲时间和占有时间
	 * 
	 * @param flag
	 * @param reqRevenueVo
	 * @return
	 */
	public Integer getPlaceUnitFreeTimeAndOccupyTime(Integer flag, ReqRevenueVo reqRevenueVo) {
		List<Integer> status = new ArrayList<>();
		if (flag.equals(1)) {
			status.add(1);
		} else if (flag.equals(2)) {
			status.add(3);
		}
		reqRevenueVo.setStatus(status);
		Integer count = tbBizPlaceOrderManagerMapper.placeUnitFreeTimeAndOccupyTimeStatistics(reqRevenueVo);
		return count;
	}

	/**
	 * 订单详情
	 * 
	 * @param placeOrderId
	 * @return
	 */
	public List<TbBizPlaceOrderItem> getTbBizPlaceOrderItem(String placeOrderId) {
		TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
		TbBizPlaceOrderItemExample.Criteria tbBizPlaceOrderItemExampleCriteria = tbBizPlaceOrderItemExample
				.createCriteria();
		tbBizPlaceOrderItemExampleCriteria.andPlaceOrderIdEqualTo(placeOrderId);
		tbBizPlaceOrderItemExample.setOrderByClause("unit_sale_plan_id");
		List<TbBizPlaceOrderItem> list = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
		return list;
	}

	/**
	 * 根据销售计划id查询订单详情
	 * 
	 * @param id
	 *            tb_biz_place_unit_sale_plan
	 * @return
	 */
	private RespProductUnitInfo getProductUnitInfo(Integer id) {
		TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = tbBizPlaceUnitSalePlanMapper.selectByPrimaryKey(id);
		RespProductUnitInfo respProductUnitInfo = new RespProductUnitInfo();
		if (null != tbBizPlaceUnitSalePlan) {
			respProductUnitInfo.setDate(tbBizPlaceUnitSalePlan.getDate());
		}
		return respProductUnitInfo;
	}

	private RespPlaceOrderDetails getPlaceOrderDetails(List<TbBizPlaceOrder> selectByExample) {
		// 响应对象
		RespPlaceOrderDetails rbpoi = new RespPlaceOrderDetails();
		// 场馆订单
		TbBizPlaceOrder tbBizPlaceOrder = selectByExample.get(0);
		rbpoi.setOrderAmount(tbBizPlaceOrder.getDebit());
		rbpoi.setPayAmount(getPayAmount(tbBizPlaceOrder.getPlaceOrderId()));
		rbpoi.setSourceType(tbBizPlaceOrder.getSourceType());// 订单来源类型 1：普通订场业务
																// 2：现场支付业务
																// 3：竞拍业务 4：约运动
	
		rbpoi.setExpression(tbBizPlaceOrder.getExpression());
		String placeOrderId = tbBizPlaceOrder.getPlaceOrderId();
		// 订单详情
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItem = getTbBizPlaceOrderItem(placeOrderId);
		if (!tbBizPlaceOrderItem.isEmpty()) {
			List<RespTicketSaleInfo> listTicketSale = new ArrayList<>();
			List<RespProductUnitInfo> listSaleUnit = new ArrayList<>();
			List<RespPlaceGoodsInfo> listGoods = new ArrayList<>();
		BigDecimal totalDiscountCoupon=new BigDecimal(0.0);
		BigDecimal toaltDiscountDiscountCoupon=new BigDecimal(0.0);
		BigDecimal totalDiscountMember=new BigDecimal(0.0);
		BigDecimal totalDiscountDiscountMember=new BigDecimal(0.0);
		BigDecimal totalDiscountAdjust=new BigDecimal(0.0);
		BigDecimal totalDiscountNumberMember=new BigDecimal(0.0);
		Integer totalEggCount=new Integer(0);
		TreeSet<Byte> useTypes=new TreeSet<>();
			for (TbBizPlaceOrderItem orderItem : tbBizPlaceOrderItem) {
				Byte userType=orderItem.getUseType();
				if (userType.equals((byte) 0) || userType.equals((byte) 1) || userType.equals((byte) 3)) {// TODO
					useTypes.add(orderItem.getUseType());	
					String saleId = orderItem.getSaleId();
					if (null != saleId) {
						RespProductUnitInfo respProductUnitInfo = getProductUnitInfoBySaleId(saleId);
						if (null != respProductUnitInfo) {

							// listPlaceOrderId.add(tbBizPlaceOrder.getPlaceOrderId());
							// map.put("placeOrderId", listPlaceOrderId);
							// BigDecimal salePrice =
							// financeCommonManagerMapper.getDiscountAmount(map);
							// listPlaceOrderId.clear();
							// map.clear();
                            
                                respProductUnitInfo.setPrice(orderItem.getSalePrice());
                            
							listSaleUnit.add(respProductUnitInfo);
							// 销售计划时间
							if (null != listSaleUnit.get(0).getDate()) {
								String setSaleDate = DateUtils.transferDateToString(listSaleUnit.get(0).getDate());
								rbpoi.setDate(setSaleDate);
							}
						}
					}
				} else if (userType.equals((byte) 2)) {// TODO 2门票
					useTypes.add(orderItem.getUseType());	
					RespTicketSaleInfo respTicketSaleInfo = new RespTicketSaleInfo();
					respTicketSaleInfo.setTicketCount(orderItem.getTicketCount());
					respTicketSaleInfo.setSalePrice(orderItem.getSalePrice());
					
					respTicketSaleInfo.setCategoryName(
							iBaseService.getCommonDataCache("cagetory" + tbBizPlaceOrder.getCategoryId().toString()));
					rbpoi.setDate(DateUtils.transferDateToString(orderItem.getConsumeTime()));
					listTicketSale.add(respTicketSaleInfo);

				} else if (userType.equals((byte) 4)) {// TODO 4商品
					useTypes.add(orderItem.getUseType());	
					RespPlaceGoodsInfo respPlaceGoodsInfo = new RespPlaceGoodsInfo();
					Integer unitSalePlanId = orderItem.getUnitSalePlanId();
					TbBizPlaceGoods tbBizPlaceGoods = tbBizPlaceGoods(unitSalePlanId);
					respPlaceGoodsInfo.setGoodsPrice(orderItem.getSalePrice());
					respPlaceGoodsInfo.setGoodsCount(orderItem.getTicketCount());
					respPlaceGoodsInfo.setGoodsName(tbBizPlaceGoods.getName());
					rbpoi.setDate(DateUtils.transferDateToString(tbBizPlaceOrder.getOrderTime()));
					listGoods.add(respPlaceGoodsInfo);

				}
				
				/*****************add start 增加优惠 ************************************************************/
				List<RespPlaceOrderDiscountItem> respPlaceOrderDiscountItems=new ArrayList<>();
				Map<String,Object> params=new HashMap<>();
				params.put("itemUuid",orderItem.getItemUuid() );
				respPlaceOrderDiscountItems.addAll(placeOrderAdminMapper.getDiscountItem(params));
				
				if(respPlaceOrderDiscountItems!=null&&respPlaceOrderDiscountItems.size()>0){
				RespPlaceOrderDiscountItem discountItem=respPlaceOrderDiscountItems.get(0);
               
                totalDiscountCoupon=totalDiscountCoupon.add(this.handleDecimalNull(discountItem.getDiscountCoupon()));
                toaltDiscountDiscountCoupon=toaltDiscountDiscountCoupon.add(this.handleDecimalNull(discountItem.getDiscountDiscountCoupon()));
                totalDiscountMember=totalDiscountMember.add(this.handleDecimalNull(discountItem.getDiscountMember()));
                totalDiscountDiscountMember=totalDiscountDiscountMember.add(this.handleDecimalNull(discountItem.getDiscountDiscountMember()));
                totalDiscountAdjust=totalDiscountAdjust.add(this.handleDecimalNull(discountItem.getDiscountAdjust()));
               if(discountItem.getEggCount()==null){
            	   discountItem.setEggCount(0);
               }
               totalEggCount=totalEggCount+discountItem.getEggCount();  
                totalDiscountNumberMember=totalDiscountNumberMember.add(this.handleDecimalNull(discountItem.getDiscountNumberMember()));//会员次卡优惠
				}
				
			}
			RespPlaceOrderDiscountItem discountItem=new RespPlaceOrderDiscountItem();
			
			discountItem.setDiscountCoupon(totalDiscountCoupon);
			discountItem.setDiscountDiscountCoupon(toaltDiscountDiscountCoupon);
			
			discountItem.setDiscountDiscountMember(totalDiscountDiscountMember);
			discountItem.setDiscountMember(totalDiscountMember);
			discountItem.setDiscountNumberMember(totalDiscountNumberMember);
			discountItem.setEggCount(totalEggCount);
			discountItem.setDiscountAdjust(totalDiscountAdjust);
			 logger.info("优惠：{}", JSON.toJSONString(discountItem));
			rbpoi.setDiscountItem(discountItem);
			/*****************end start 增加优惠 ************************************************************/
			Byte[] array =new Byte[useTypes.size()];
			rbpoi.setUseType(useTypes.toArray(array));// 0开单 1包场 2门票 4商品
			rbpoi.setDescrible(tbBizPlaceOrder.getDescrible());
			rbpoi.setRespTicketSaleInfo(listTicketSale);
			rbpoi.setRespPlaceGoodsInfos(listGoods);
            Comparator<RespProductUnitInfo> productUnitInfoComparator = new Comparator<RespProductUnitInfo>() {
                @Override
                public int compare(RespProductUnitInfo o1, RespProductUnitInfo o2) {
                    if (!o1.getPlaceUnitName().equals(o2.getPlaceUnitName())){
                        return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());
                    }
                    return o1.getStartTime().compareTo(o2.getStartTime());

                }
            };
            Collections.sort(listSaleUnit,productUnitInfoComparator);
            logger.info("订单详情时间排序：{}",JSON.toJSONString(listSaleUnit));
			rbpoi.setProductUnits(listSaleUnit);
		}
		return rbpoi;
	}


    private TbBizPlaceGoods tbBizPlaceGoods(Integer goodId) {
		return tbBizPlaceGoodsMapper.selectByPrimaryKey(goodId);
	}

	/**
	 * 订单详情
	 * 
	 * @param reqPlaceOrderDetailVo
	 * @return
	 */
	@Override
	public RespPlaceOrderDetails placeOrderMessageDetail(ReqPlaceOrderDetailVo reqPlaceOrderDetailVo) {
		String orderNo = reqPlaceOrderDetailVo.getOrderNo();
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
		tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
		tbBizPlaceOrderExampleCriteria.andIsEffectiveEqualTo((byte) 1);// TODO
																		// 是否有效
		List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		// 响应对象
		RespPlaceOrderDetails rbpoi = null;
		if (!selectByExample.isEmpty()) {
			rbpoi = getPlaceOrderDetails(selectByExample);
		} else {
			TbBizPlacePrivateOrderExample tbBizPlacePrivateOrderExample = new TbBizPlacePrivateOrderExample();
			TbBizPlacePrivateOrderExample.Criteria criteria = tbBizPlacePrivateOrderExample.createCriteria();
			criteria.andPlaceOrderIdEqualTo(orderNo);
			List<TbBizPlacePrivateOrder> tbBizPlacePrivateOrders = tbBizPlacePrivateOrderMapper
					.selectByExample(tbBizPlacePrivateOrderExample);
			if (tbBizPlacePrivateOrders != null) {
				TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrders.get(0);
				Integer id = tbBizPlacePrivateOrder.getId();
				TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
				TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria1 = tbBizPlaceOrderExample1
						.createCriteria();
				tbBizPlaceOrderExampleCriteria1.andParentIdEqualTo(id);
				tbBizPlaceOrderExampleCriteria1.andIsEffectiveEqualTo((byte) 1);// TODO
																				// 是否有效
				List<TbBizPlaceOrder> selectByExample1 = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample1);
				if (!selectByExample1.isEmpty()) {
					rbpoi = getPlaceOrderDetails(selectByExample1);
					// rbpoi.setExpression();
				}
			}
		}
		List<TbBizPlacePayItem> payItem = getPayItem(orderNo, PlaceConstants.PAY_WAY_FOR_CARD);
		if (null != payItem && payItem.size() > 0) {
			TbBizPlacePayItem tbBizPlacePayItem = payItem.get(0);
			if (null != tbBizPlacePayItem.getSubjectCode()) {
				TbBizPlaceMemberCard tbBizPlaceMemberCard = getPlaceMemberInfo(tbBizPlacePayItem.getSubjectCode());
				RespOrderMemberCard respOrderMemberCard = new RespOrderMemberCard();
				respOrderMemberCard.setCardType(tbBizPlaceMemberCard.getCardType());
				respOrderMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount());
				respOrderMemberCard.setSurplusNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
				rbpoi.setRespOrderMemberCard(respOrderMemberCard);
			}
		}
		return rbpoi;
	}



	public TbBizPlaceMemberCard getPlaceMemberInfo(String cardNo) {
		TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
		TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample
				.createCriteria();
		if (!StringUtils.isEmpty(cardNo)) {
			tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(cardNo);
		}
		// tbBizPlaceMemberCardCriteria.andDeadLineTimeGreaterThan(new
		// Date());//判断截止日期
		tbBizPlaceMemberCardCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
		// tbBizPlaceMemberCardCriteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);//卡状态
		// tbBizPlaceMemberCardCriteria.andCardTypeEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER);//TODO次卡
		// tbBizPlaceMemberCardCriteria.andSourceTypeEqualTo(PlaceConstants.PLACE_MEMBER);//普通会员
		List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper
				.selectByExample(tbBizPlaceMemberCardExample);
		return tbBizPlaceMemberCardList.get(0);
	}

	public List<TbBizPlacePayItem> getPayItem(String orderNo, Integer payType) {
		TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
		TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
		tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(orderNo);
		if (null != payType) {
			tbBizPlacePayItemCriteria.andPayTypeEqualTo(payType);
		}
		List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper
				.selectByExample(tbBizPlacePayItemExample);
		return tbBizPlacePayItemList;

	}

	public BigDecimal getPayAmount(String orderNo) {
		List<Integer> values = new ArrayList<>();
		values.add(PlaceConstants.PAY_WAY_ALIPAY);
		values.add(PlaceConstants.PAY_WAY_WEICHAT);
		values.add(PlaceConstants.PAY_WAY_WEICHATH5);
		values.add(PlaceConstants.PAY_WAY_UNION_PAY);
		values.add(PlaceConstants.PAY_WAY_APPLE_PAY);

		TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
		TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
		tbBizPlacePayItemCriteria.andPayTypeIn(values);
		tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(orderNo);

		List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper
				.selectByExample(tbBizPlacePayItemExample);
		if (!CollectionUtils.isEmpty(tbBizPlacePayItemList)) {
			return tbBizPlacePayItemList.get(0).getAmount();
		}
		return new BigDecimal(0.0);

	}

	/**
	 * 封装用户信息
	 * 
	 * @param //tbBizPlaceOrder
	 * @return
	 */
	/*
	 * private RespPlaceUserInfo getPlaceUserInfo(TbBizPlaceOrder
	 * tbBizPlaceOrder){ RespPlaceUserInfo respPlaceUserInfo = new
	 * RespPlaceUserInfo();
	 * //respPlaceUserInfo.setUid(tbBizPlaceOrder.getUid());// TODO 场馆订单列表用户待封装
	 * respPlaceUserInfo.setNickName(tbBizPlaceOrder.getCustomerName());
	 * respPlaceUserInfo.setMobile(tbBizPlaceOrder.getMobile());
	 * respPlaceUserInfo.setIsMaster(0); respPlaceUserInfo.setLevel(0);
	 * respPlaceUserInfo.setIcon(""); APIResponse<RespUserInfoBase> result =
	 * null; try { result =
	 * userServiceFacade.queryUserInfo(tbBizPlaceOrder.getUid());
	 * RespUserInfoBase respUserInfoBase = result.getData(); if (null !=
	 * respUserInfoBase){
	 * respPlaceUserInfo.setNickName(respUserInfoBase.getNickName());
	 * respPlaceUserInfo.setMobile(respUserInfoBase.getMobile()); } } catch
	 * (Exception e) { e.printStackTrace(); } return respPlaceUserInfo; }
	 */

	/*
	 * private Long getStartDate(Integer uid, String orderNo,Integer
	 * unsubscribeTime){ Map<String,Object> queryMap = new HashMap<>();
	 * queryMap.put("orderNo",orderNo); queryMap.put("uid", uid);
	 * List<PlaceOrderSalePlan> placeOrderSalePlanList =
	 * tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap); if
	 * (!CollectionUtils.isEmpty(placeOrderSalePlanList)){ String startTime =
	 * placeOrderSalePlanList.get(0).getStartTime(); String startDate =
	 * placeOrderSalePlanList.get(0).getDate(); Date date =
	 * DateUtils.dateStrToDate(startDate + " " + startTime); if(unsubscribeTime
	 * > 0){ return date.getTime() - unsubscribeTime*60*60*1000; } return
	 * PlaceConstants.NOT_UNSUBSCRIBE_TIMESTAMP; } return 0L; }
	 */

	private RespProductUnitInfo getProductUnitInfoBySaleId(String saleId) {
		TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
		TbBizPlaceUnitSalePlanExample.Criteria criteria = tbBizPlaceUnitSalePlanExample.createCriteria();
		criteria.andSaleIdEqualTo(saleId);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = tbBizPlaceUnitSalePlanMapper
				.selectByExample(tbBizPlaceUnitSalePlanExample);
		RespProductUnitInfo respProductUnitInfo = null;
		if (tbBizPlaceUnitSalePlans != null && tbBizPlaceUnitSalePlans.size() > 0) {
			TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = tbBizPlaceUnitSalePlans.get(0);
			if (null != tbBizPlaceUnitSalePlan) {
				respProductUnitInfo = new RespProductUnitInfo();
				respProductUnitInfo.setStartTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()));
				respProductUnitInfo.setEndTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));
				respProductUnitInfo.setPlaceUnitName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
				respProductUnitInfo.setDate(tbBizPlaceUnitSalePlan.getDate());
				respProductUnitInfo.setCategoryName(iBaseService
						.getCommonDataCache("cagetory" + tbBizPlaceUnitSalePlan.getCategoryId().toString()));
				respProductUnitInfo.setCategoryId(tbBizPlaceUnitSalePlan.getCategoryId());
				respProductUnitInfo.setSaleId(tbBizPlaceUnitSalePlan.getId() + "");
				respProductUnitInfo.setDetailsTime(tbBizPlaceUnitSalePlan.getDate());// 销售计划时间
				respProductUnitInfo.setCreateTime(tbBizPlaceUnitSalePlan.getCreateTime());
				respProductUnitInfo.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
				respProductUnitInfo.setPrice(tbBizPlaceUnitSalePlan.getPrice());
			}
		}
		return respProductUnitInfo;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public APIResponse<RespPreOrder> placeScanPay(ReqScanPay reqScanPay) throws Exception {
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqScanPay.getPlaceId());
		if (org.springframework.util.StringUtils.isEmpty(tbBizPlace)) {
			throw new BizException("没有相关场馆信息");
		}
		// 设置回调方式
		TbCommonParameter parameter = baseService
				.getParameterByKey(SysParameterConfigEnum.PLACE_ORDER_CALLBACK_TYPE.getCode());
		Integer callbackType = 0;
		if (parameter != null && parameter.getParameterValue() != null) {
			callbackType = Integer.valueOf(parameter.getParameterValue());
		}
		// 调用订单系统，获取预支付信息
		com.quanyan.api.APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new com.quanyan.api.APIRequest<>();
		ReqOrderSave reqOrderSave = new ReqOrderSave();
		reqOrderSaveAPIRequest.setData(reqOrderSave);
		reqOrderSave.setSourceBusinessId(reqScanPay.getSourceBusinessId());
		reqOrderSave.setSourceSystemId(Constants.PLACE_SYSTEM_CODE);
		reqOrderSave.setPlatformType(PlatformTypeEnum.BACKSTAGE.getId());// 设置平台类型
		reqOrderSave.setContactMobile(reqScanPay.getMobile());
		reqOrderSave.setContactName(reqScanPay.getUserName());
		reqOrderSave.setExtraParam("");
		reqOrderSave.setAuthCode(reqScanPay.getScanCode());
		if (tbBizPlace.getCityId() != null && tbBizPlace.getCityId().equals(3)) {
			reqOrderSave.setMchId(3); // 此处为城市ID，必填
		} else {
			reqOrderSave.setMchId(2); // 此处为城市ID，必填
		}
		// 如果回调类型为0，则订单系统使用http方式进行回调；如果回调类型为1，使用mq进行处理
		if (callbackType.equals(Constants.IS_NO)) {
			reqOrderSave.setNotifyURL(payUrl);
			reqOrderSave.setCloseNotifyURL(closeOrderUrl);
			reqOrderSave.setRefundNotifyURL(refundUrl);
			reqOrderSave.setPayConfirmNotifyURL(payConfirmUrl);
			// reqOrderSave.setExceptionRefundNotify(exceptionRefundUrl);
			logger.warn("订单号：{}，支付使用http回调处理。", reqScanPay.getOrderNo());
		} else {
			logger.warn("订单号：{}，支付使用mq消息处理。", reqScanPay.getOrderNo());
		}

		reqOrderSave.setOrderDescribe(reqScanPay.getProductName());
		reqOrderSave.setOrderURL(tbBizPlace.getBizPlaceUrl());
		reqOrderSave.setOutTradeNo(reqScanPay.getOrderNo());
		reqOrderSave.setPayNote("");
		reqOrderSave.setUserClientIp("");
		reqOrderSave.setPayTimeOut(PlaceConstants.PAYTIMEOUT_MINUTE);// 超时1分钟
		reqOrderSave.setUid(reqScanPay.getCreateUid());
		reqOrderSave.setShowURL(tbBizPlace.getBizPlaceUrl());
		reqOrderSave.setService(PlaceConstants.SERVICE_CODE);

		List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
		ReqProductDetail reqProductDetail = new ReqProductDetail();
		reqProductDetail.setShowURL(tbBizPlace.getBizPlaceUrl());
		reqProductDetail.setProductDesc(reqScanPay.getProductDesc());
		reqProductDetail.setProductId(reqScanPay.getProductId());
		reqProductDetail.setProductName(reqScanPay.getProductName());
		reqProductDetail.setProductURL(tbBizPlace.getBizPlaceUrl());
		reqProductDetail.setQuantity(1);
		reqProductDetailList.add(reqProductDetail);
		reqOrderSave.setProductDetailList(reqProductDetailList);

		List<ReqPayInfo> payInfos = new ArrayList<>();
		ReqPayInfo reqPayInfo = new ReqPayInfo();
		reqPayInfo.setPayId(reqScanPay.getPayWay());
		reqPayInfo.setAmount(reqScanPay.getAmount());
		reqPayInfo.setPayType(reqScanPay.getPayType());
		payInfos.add(reqPayInfo);
		reqOrderSave.setOrderAmount(reqScanPay.getAmount());

		reqOrderSave.setPayInfos(payInfos);
		reqOrderSave.setSubmitDate(new Date());
		logger.warn("========================支付数据:reqOrderSave:{}", JSON.toJSONString(reqOrderSave));
		APIResponse<RespPreOrder> respPreOrderAPIResponse = orderPayService.submitOrder(reqOrderSaveAPIRequest);
		try {
			if (respPreOrderAPIResponse == null || !respPreOrderAPIResponse.isRet()) {
				throw new BizException(respPreOrderAPIResponse.getErrmsg());
			}
		} catch (Exception e) {
			if (respPreOrderAPIResponse != null && !respPreOrderAPIResponse.isRet()) {
				logger.warn("uid：{} ，error：{} ", reqScanPay.getCreateUid(), respPreOrderAPIResponse.getErrmsg());
			} else {
				logger.warn("uid：{} ，error：{} ", reqScanPay.getCreateUid(), e.getMessage());
			}
			throw new BizException(respPreOrderAPIResponse.getErrmsg());
		}
		logger.warn("========================支付回调数据:reqOrderSave:{}", JSON.toJSONString(respPreOrderAPIResponse));
		String orderSystemOrderNo = respPreOrderAPIResponse.getData().getOrderNo();
		Date payTime = null;
		if (OrderStatusEnum.USER_PAY_SUCCESS.getCode().equals(respPreOrderAPIResponse.getData().getResult())) {
			payTime = new Date(respPreOrderAPIResponse.getData().getPayTime());
		}
		if (!org.springframework.util.StringUtils.isEmpty(reqScanPay.getTbBizPlaceOrder())) {
			TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
			tbBizPlaceOrderExample.createCriteria()
					.andPlaceOrderIdEqualTo(reqScanPay.getTbBizPlaceOrder().getPlaceOrderId());
			tbBizPlaceOrderExample.setOrderByClause(" id for update ");
			List<TbBizPlaceOrder> bizPlaceOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
			if (CollectionUtils.isEmpty(bizPlaceOrderList)) {
				return APIResponse.returnFail("找不到该订单！");
			}
			bizPlaceOrderList.get(0).setOrderNo(orderSystemOrderNo);
			if (payTime != null) {
				bizPlaceOrderList.get(0).setPaymentTime(payTime);
			}
			tbBizPlaceOrderMapper.updateByPrimaryKeySelective(bizPlaceOrderList.get(0));
		} else if (!org.springframework.util.StringUtils.isEmpty(reqScanPay.getTbBizPlacePrivateOrder())) {
			TbBizPlacePrivateOrderExample tbBizPlacePrivateOrderExample = new TbBizPlacePrivateOrderExample();
			tbBizPlacePrivateOrderExample.createCriteria()
					.andPlaceOrderIdEqualTo(reqScanPay.getTbBizPlacePrivateOrder().getPlaceOrderId());
			tbBizPlacePrivateOrderExample.setOrderByClause(" id for update ");
			List<TbBizPlacePrivateOrder> tbBizPlacePrivateOrderList = tbBizPlacePrivateOrderMapper
					.selectByExample(tbBizPlacePrivateOrderExample);
			if (CollectionUtils.isEmpty(tbBizPlacePrivateOrderList)) {
				return APIResponse.returnFail("找不到该订单！");
			}
			tbBizPlacePrivateOrderList.get(0).setOrderNo(orderSystemOrderNo);
			if (payTime != null) {
				tbBizPlacePrivateOrderList.get(0).setPaymentTime(payTime);
			}
			tbBizPlacePrivateOrderMapper.updateByPrimaryKeySelective(tbBizPlacePrivateOrderList.get(0));
		} else if (!org.springframework.util.StringUtils.isEmpty(reqScanPay.getTbBizPlaceMemberOpHistory())) {
			// 更新会员交易明细订单号
			TbBizPlaceMemberOpHistoryExample historyExample = new TbBizPlaceMemberOpHistoryExample();
			historyExample.createCriteria().andOrderNoEqualTo(reqScanPay.getTbBizPlaceMemberOpHistory().getOrderNo());
			historyExample.setOrderByClause(" id for update ");
			List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistories = tbBizPlaceMemberOpHistoryMapper
					.selectByExample(historyExample);
			if (CollectionUtils.isEmpty(tbBizPlaceMemberOpHistories)) {
				return APIResponse.returnFail("找不到该流水！");
			}
			tbBizPlaceMemberOpHistories.get(0).setNo(orderSystemOrderNo);
			if (payTime != null) {
				tbBizPlaceMemberOpHistories.get(0).setPaymentTime(payTime);
			}
			tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKeySelective(tbBizPlaceMemberOpHistories.get(0));
		}
		//
		// if (!StringUtils.isEmpty(reqScanPay.getTbBizPlaceOrder())){
		// reqScanPay.getTbBizPlaceOrder().setOrderNo(orderSystemOrderNo);
		// if
		// (OrderStatusEnum.USER_PAY_SUCCESS.getCode().equals(respPreOrderAPIResponse.getData().getResult())){
		// reqScanPay.getTbBizPlaceOrder().setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		// reqScanPay.getTbBizPlaceOrder().setPayStatus(PlaceConstants.PAY_STATUS);
		// }
		// }else
		// if(!StringUtils.isEmpty(reqScanPay.getTbBizPlacePrivateOrder())){
		// reqScanPay.getTbBizPlacePrivateOrder().setOrderNo(orderSystemOrderNo);
		// if
		// (OrderStatusEnum.USER_PAY_SUCCESS.getCode().equals(respPreOrderAPIResponse.getData().getResult())){
		// reqScanPay.getTbBizPlacePrivateOrder().setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		// reqScanPay.getTbBizPlacePrivateOrder().setPayStatus(PlaceConstants.PAY_STATUS);
		// }
		// }else if
		// (OrderStatusEnum.WAIT_BUYPER_PAY.getCode().equals(respPreOrderAPIResponse.getData().getResult())){
		// //等待支付
		// }
		// OrderStatusEnum.USER_PAY_SUCCESS.getCode()
		// OrderStatusEnum.WAIT_BUYPER_PAY.getCode()
		return respPreOrderAPIResponse;
	}
	
	/**
     * 业务走完走订单系统扫码支付
     * @param placeScanOrderPayVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?>  scanBlockOrderPay(PlaceScanOrderPayVo placeScanOrderPayVo) throws Exception{
        ReqScanPay reqScanPay = new ReqScanPay();

        reqScanPay.setAmount(placeScanOrderPayVo.getReceivedAmount());
    	if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(placeScanOrderPayVo.getAdminPayType())) {  //增加银联pos支付 add by tim
    		reqScanPay.setPayWay(PayWayEnum.PAY_WAY_WEICHAT_SCAN.getPayId());
		}else if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(placeScanOrderPayVo.getAdminPayType())){
			reqScanPay.setPayWay(PayWayEnum.PAY_WAY_ALIPAY_SCAN.getPayId());
		}else if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(placeScanOrderPayVo.getAdminPayType())){
			reqScanPay.setPayWay(PayWayEnum.PAY_WAY_UNION_PAY_POS.getPayId());
		}
        reqScanPay.setScanCode(placeScanOrderPayVo.getScanCode());
        reqScanPay.setSourceBusinessId(Constants.PLACE_SCANPAY_CODE);

        //包场业务
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = placeScanOrderPayVo.getTbBizPlacePrivateOrder();
        //普通订单业务
        TbBizPlaceOrder tbBizPlaceOrder = placeScanOrderPayVo.getTbBizPlaceOrder();
        //会员充值业务
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = placeScanOrderPayVo.getTbBizPlaceMemberOpHistory();
        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeScanOrderPayVo.getTbBizPlaceMemberCard();

        if (tbBizPlacePrivateOrder==null&&tbBizPlaceOrder==null&&tbBizPlaceMemberOpHistory==null&&tbBizPlaceMemberCard==null){
            return APIResponse.returnFail("不存在该业务订单");
        }

        //包场业务--支付下单
        if (tbBizPlacePrivateOrder != null){
            reqScanPay.setOrderNo(tbBizPlacePrivateOrder.getPlaceOrderId());
            reqScanPay.setProductId(tbBizPlacePrivateOrder.getPlaceOrderId());//订单号
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlacePrivateOrder.getPlaceId());
            reqScanPay.setTbBizPlacePrivateOrder(tbBizPlacePrivateOrder);
            reqScanPay.setPlaceId(tbBizPlacePrivateOrder.getPlaceId());
            reqScanPay.setCreateUid(tbBizPlacePrivateOrder.getCreateUid());
            reqScanPay.setMobile(tbBizPlacePrivateOrder.getMobile());
            reqScanPay.setUserName(StringUtil.isBlankOrNull(tbBizPlacePrivateOrder.getCustomerName()) ? "散客":tbBizPlacePrivateOrder.getCustomerName());

            reqScanPay.setProductDesc("包场-"+tbBizPlacePrivateOrder.getDescrible());
            reqScanPay.setPayType("包场扫码支付");
            reqScanPay.setProductName(tbBizPlace.getName()
                    +iBaseService.getCommonDataCache("cagetory" + tbBizPlacePrivateOrder.getCategoryId())
                    +"场地包场");
        }

        //普通订单业务、包场子订单
        if (tbBizPlaceOrder != null){
            reqScanPay.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());
            reqScanPay.setProductId(tbBizPlaceOrder.getPlaceOrderId());//订单号
            reqScanPay.setPlaceId(tbBizPlaceOrder.getPlaceId());
            reqScanPay.setCreateUid(tbBizPlaceOrder.getCreateUid());
            reqScanPay.setMobile(tbBizPlaceOrder.getMobile());
            reqScanPay.setUserName(StringUtil.isBlankOrNull(tbBizPlaceOrder.getCustomerName()) ? "散客":tbBizPlaceOrder.getCustomerName());
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceOrder.getPlaceId());
            
            TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
			tbBizPlaceOrderItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrder.getPlaceOrderId());
			List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
			
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING) 
            		|| tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
				//预订后再支付  修改调价 
				if (placeScanOrderPayVo.getReceivedAmount() != null){
					if(!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(placeScanOrderPayVo.getAdminPayType())){//非银联pos走这块代码
						if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			            	    //实付金额
								BigDecimal realAmount = new BigDecimal(0);
				 				for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
									realAmount = realAmount.add(tbBizPlaceOrderItem.getSalePrice());
								}
				 				
				 				//订单明细调价
				 				List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = 
				 						iBaseService.adjustOrderItemPrice(placeScanOrderPayVo.getReceivedAmount(),tbBizPlaceOrderItemList,realAmount);
				 				for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
				 					tbBizPlaceOrderItemMapper.updateByPrimaryKeySelective(item);
				 				}
				 				
								tbBizPlaceOrder.setHandAdjustAmount(placeScanOrderPayVo.getReceivedAmount().subtract(realAmount));
								tbBizPlaceOrderMapper.updateByPrimaryKey(tbBizPlaceOrder);
						}
					}
					
				}


                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("开单-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("开单扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +iBaseService.getCommonDataCache("cagetory" + tbBizPlaceOrder.getCategoryId())
                        +"场地开单");
            }
            
            //对于包场订单未完成支付进行日订单支付
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("包场-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("包场扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +iBaseService.getCommonDataCache("cagetory" + tbBizPlaceOrder.getCategoryId())
                        +"场地包场");
            }
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
         
            	
                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("门票-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("门票扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +iBaseService.getCommonDataCache("cagetory" + tbBizPlaceOrder.getCategoryId())
                        +"门票");
            }
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            	
                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("商品-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("商品扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +"商品购买");
            }
			if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){

				reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
				reqScanPay.setProductDesc("购物车-"+tbBizPlaceOrder.getDescrible());
				reqScanPay.setPayType("购物车扫码支付");
				reqScanPay.setProductName(tbBizPlace.getName()
						+"购物车支付");
			}
        }

        if (tbBizPlaceMemberOpHistory!=null&&tbBizPlaceMemberCard!=null){
            reqScanPay.setOrderNo(tbBizPlaceMemberOpHistory.getOrderNo());
            reqScanPay.setProductId(tbBizPlaceMemberOpHistory.getOrderNo());//订单号
            reqScanPay.setPlaceId(tbBizPlaceMemberOpHistory.getPlaceId());
            reqScanPay.setCreateUid(tbBizPlaceMemberOpHistory.getCreateUid());
            reqScanPay.setMobile(tbBizPlaceMemberOpHistory.getMobile());
            reqScanPay.setUserName(tbBizPlaceMemberOpHistory.getUserName());
            reqScanPay.setProductDesc("会员充值-"+tbBizPlaceMemberOpHistory.getMemo());
            reqScanPay.setPayType("会员充值扫码支付");
            reqScanPay.setProductName(tbBizPlaceMemberOpHistory.getOpTypeName());
            reqScanPay.setTbBizPlaceMemberCard(tbBizPlaceMemberCard);
            reqScanPay.setTbBizPlaceMemberOpHistory(tbBizPlaceMemberOpHistory);
        }

        try {
            APIResponse<RespPreOrder> preOrderResponse = this.placeScanPay(reqScanPay);
            if(preOrderResponse.isRet() && preOrderResponse != null){
                if (preOrderResponse.getData().getResult().equals(OrderStatusEnum.USER_PAY_SUCCESS.getCode())){
                    ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
                    reqOrderOperate.setUpdateStock(true);
                    reqOrderOperate.setPayTime(new Date(preOrderResponse.getData().getPayTime()));
                    PlacePrintVo placePrintVo = new PlacePrintVo();
                    //包场业务--支付下单
                    if (tbBizPlacePrivateOrder != null){
                        reqOrderOperate.setOrderNo(tbBizPlacePrivateOrder.getPlaceOrderId());
                        //包场回调
                        placeOrderCallbackService.bookAllOrderCompletePayOperate(reqOrderOperate);
                        placePrintVo.setPlacePrivateOrderId(tbBizPlacePrivateOrder.getPlaceOrderId());
                        placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
                        placePrintVo.setIsMember(PlaceConstants.NO);
                    }
                    //普通订单业务、包场子订单
                    if (tbBizPlaceOrder != null){
                        reqOrderOperate.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
                            //开单回调
                            placeOrderCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BILLING);
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
                        //对于包场订单未完成支付进行日订单支付
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
                            //包场回调
                            placeOrderCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);//认为是开单再支付
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
                            //门票回调
                            placeOrderCallbackService.ticketOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_TICKET);
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
                            //商品回调
                            placeOrderCallbackService.goodsOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_GOODS);
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
						if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
							//购物车回调
							placeOrderCallbackService.shoppingCartOrderCompletePayOperate(reqOrderOperate);
							placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
							placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_SHOPPING_CART);
							placePrintVo.setIsMember(PlaceConstants.NO);
						}
                    }
                    //会员充值业务
                    if (tbBizPlaceMemberOpHistory!=null&&tbBizPlaceMemberCard!=null){
                        reqOrderOperate.setOrderNo(tbBizPlaceMemberOpHistory.getOrderNo());
                        //tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                        placeOrderCallbackService.cardOrderCompletePayOperate(reqOrderOperate);
                        placePrintVo.setPlaceOrderId(tbBizPlaceMemberOpHistory.getOrderNo());
                        if (tbBizPlaceMemberOpHistory.getSrc().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN)){
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_OPEN_CARD);
                        }
                        if (tbBizPlaceMemberOpHistory.getSrc().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE)){
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_RECHARGE_CARD);
                        }
                        placePrintVo.setIsMember(PlaceConstants.NO);
                    }
                    return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
                }else if(preOrderResponse.getData().getResult().equals(OrderStatusEnum.WAIT_BUYPER_PAY.getCode())){
                    //add start 银联pos支付返回条形码处理页面,获取pos条形码信息
					APIResponse<?> data = getUnionPosBarCodeInfo(placeScanOrderPayVo, reqScanPay, preOrderResponse);
					if (data != null) return data;
					//add end


					if (tbBizPlaceOrder != null){
                        return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY,tbBizPlaceOrder.getPlaceOrderId(),tbBizPlaceOrder.getPlaceOrderId());
                    }
                    if (tbBizPlacePrivateOrder != null){
                        return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY,tbBizPlacePrivateOrder.getPlaceOrderId(),tbBizPlacePrivateOrder.getPlaceOrderId());
                    }
                    if (tbBizPlaceMemberOpHistory!=null&&tbBizPlaceMemberCard!=null){
                        return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY,tbBizPlaceMemberOpHistory.getOrderNo(),tbBizPlaceMemberOpHistory.getOrderNo());
                    }

                }else{
                    logger.warn("订单系统返回：" + JSON.toJSONString(preOrderResponse));
                    return APIResponse.returnFail(preOrderResponse.getErrmsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail(e.getMessage());
        }
        return APIResponse.returnFail("查询不到该业务记录");
    }

	/**
     * 业务走完走订单系统扫码支付
     * @param placeScanOrderPayVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?>  scanOrderPay(PlaceScanOrderPayVo placeScanOrderPayVo) throws Exception{
        ReqScanPay reqScanPay = new ReqScanPay();

        reqScanPay.setAmount(placeScanOrderPayVo.getReceivedAmount());
    	if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(placeScanOrderPayVo.getAdminPayType())) {  //增加银联pos支付 add by tim
    		reqScanPay.setPayWay(PayWayEnum.PAY_WAY_WEICHAT_SCAN.getPayId());
		}else if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(placeScanOrderPayVo.getAdminPayType())){
			reqScanPay.setPayWay(PayWayEnum.PAY_WAY_ALIPAY_SCAN.getPayId());
		}else if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(placeScanOrderPayVo.getAdminPayType())){
			reqScanPay.setPayWay(PayWayEnum.PAY_WAY_UNION_PAY_POS.getPayId());
		}
        reqScanPay.setScanCode(placeScanOrderPayVo.getScanCode());
        reqScanPay.setSourceBusinessId(Constants.PLACE_SCANPAY_CODE);

        //包场业务
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = placeScanOrderPayVo.getTbBizPlacePrivateOrder();
        //普通订单业务
        TbBizPlaceOrder tbBizPlaceOrder = placeScanOrderPayVo.getTbBizPlaceOrder();
        //会员充值业务
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = placeScanOrderPayVo.getTbBizPlaceMemberOpHistory();
        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeScanOrderPayVo.getTbBizPlaceMemberCard();

        if (tbBizPlacePrivateOrder==null&&tbBizPlaceOrder==null&&tbBizPlaceMemberOpHistory==null&&tbBizPlaceMemberCard==null){
            return APIResponse.returnFail("不存在该业务订单");
        }

        //包场业务--支付下单
        if (tbBizPlacePrivateOrder != null){
            reqScanPay.setOrderNo(tbBizPlacePrivateOrder.getPlaceOrderId());
            reqScanPay.setProductId(tbBizPlacePrivateOrder.getPlaceOrderId());//订单号
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlacePrivateOrder.getPlaceId());
            reqScanPay.setTbBizPlacePrivateOrder(tbBizPlacePrivateOrder);
            reqScanPay.setPlaceId(tbBizPlacePrivateOrder.getPlaceId());
            reqScanPay.setCreateUid(tbBizPlacePrivateOrder.getCreateUid());
            reqScanPay.setMobile(tbBizPlacePrivateOrder.getMobile());
            reqScanPay.setUserName(StringUtil.isBlankOrNull(tbBizPlacePrivateOrder.getCustomerName()) ? "散客":tbBizPlacePrivateOrder.getCustomerName());

            reqScanPay.setProductDesc("包场-"+tbBizPlacePrivateOrder.getDescrible());
            reqScanPay.setPayType("包场扫码支付");
            reqScanPay.setProductName(tbBizPlace.getName()
                    +iBaseService.getCommonDataCache("cagetory" + tbBizPlacePrivateOrder.getCategoryId())
                    +"场地包场");
        }

        //普通订单业务、包场子订单
        if (tbBizPlaceOrder != null){
            reqScanPay.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());
            reqScanPay.setProductId(tbBizPlaceOrder.getPlaceOrderId());//订单号
            reqScanPay.setPlaceId(tbBizPlaceOrder.getPlaceId());
            reqScanPay.setCreateUid(tbBizPlaceOrder.getCreateUid());
            reqScanPay.setMobile(tbBizPlaceOrder.getMobile());
            reqScanPay.setUserName(StringUtil.isBlankOrNull(tbBizPlaceOrder.getCustomerName()) ? "散客":tbBizPlaceOrder.getCustomerName());
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceOrder.getPlaceId());
            
            TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
			tbBizPlaceOrderItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrder.getPlaceOrderId());
			List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
			
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING) 
            		|| tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
				/*//预订后再支付  修改调价
				if (placeScanOrderPayVo.getReceivedAmount() != null){
					if(!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(placeScanOrderPayVo.getAdminPayType())){//非银联pos走这块代码
						if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			            	//实付金额
								BigDecimal realAmount = new BigDecimal(0);
				 				for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
									realAmount = realAmount.add(tbBizPlaceOrderItem.getSalePrice());
								}
								tbBizPlaceOrder.setHandAdjustAmount(placeScanOrderPayVo.getReceivedAmount().subtract(realAmount));
								tbBizPlaceOrderMapper.updateByPrimaryKey(tbBizPlaceOrder);
						}
					}
					
				}*/


                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("开单-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("开单扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +iBaseService.getCommonDataCache("cagetory" + tbBizPlaceOrder.getCategoryId())
                        +"场地开单");
            }
            
            //对于包场订单未完成支付进行日订单支付
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("包场-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("包场扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +iBaseService.getCommonDataCache("cagetory" + tbBizPlaceOrder.getCategoryId())
                        +"场地包场");
            }
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
         
            	
                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("门票-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("门票扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +iBaseService.getCommonDataCache("cagetory" + tbBizPlaceOrder.getCategoryId())
                        +"门票");
            }
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            	
                reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
                reqScanPay.setProductDesc("商品-"+tbBizPlaceOrder.getDescrible());
                reqScanPay.setPayType("商品扫码支付");
                reqScanPay.setProductName(tbBizPlace.getName()
                        +"商品购买");
            }
			if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){

				reqScanPay.setTbBizPlaceOrder(tbBizPlaceOrder);
				reqScanPay.setProductDesc("购物车-"+tbBizPlaceOrder.getDescrible());
				reqScanPay.setPayType("购物车扫码支付");
				reqScanPay.setProductName(tbBizPlace.getName()
						+"购物车支付");
			}
        }

        if (tbBizPlaceMemberOpHistory!=null&&tbBizPlaceMemberCard!=null){
            reqScanPay.setOrderNo(tbBizPlaceMemberOpHistory.getOrderNo());
            reqScanPay.setProductId(tbBizPlaceMemberOpHistory.getOrderNo());//订单号
            reqScanPay.setPlaceId(tbBizPlaceMemberOpHistory.getPlaceId());
            reqScanPay.setCreateUid(tbBizPlaceMemberOpHistory.getCreateUid());
            reqScanPay.setMobile(tbBizPlaceMemberOpHistory.getMobile());
            reqScanPay.setUserName(tbBizPlaceMemberOpHistory.getUserName());
            reqScanPay.setProductDesc("会员充值-"+tbBizPlaceMemberOpHistory.getMemo());
            reqScanPay.setPayType("会员充值扫码支付");
            reqScanPay.setProductName(tbBizPlaceMemberOpHistory.getOpTypeName());
            reqScanPay.setTbBizPlaceMemberCard(tbBizPlaceMemberCard);
            reqScanPay.setTbBizPlaceMemberOpHistory(tbBizPlaceMemberOpHistory);
        }

        try {
            APIResponse<RespPreOrder> preOrderResponse = this.placeScanPay(reqScanPay);
            if(preOrderResponse.isRet() && preOrderResponse != null){
                if (preOrderResponse.getData().getResult().equals(OrderStatusEnum.USER_PAY_SUCCESS.getCode())){
                    ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
                    reqOrderOperate.setUpdateStock(true);
                    reqOrderOperate.setPayTime(new Date(preOrderResponse.getData().getPayTime()));
                    PlacePrintVo placePrintVo = new PlacePrintVo();
                    //包场业务--支付下单
                    if (tbBizPlacePrivateOrder != null){
                        reqOrderOperate.setOrderNo(tbBizPlacePrivateOrder.getPlaceOrderId());
                        //包场回调
                        placeOrderCallbackService.bookAllOrderCompletePayOperate(reqOrderOperate);
                        placePrintVo.setPlacePrivateOrderId(tbBizPlacePrivateOrder.getPlaceOrderId());
                        placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
                        placePrintVo.setIsMember(PlaceConstants.NO);
                    }
                    //普通订单业务、包场子订单
                    if (tbBizPlaceOrder != null){
                        reqOrderOperate.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
                            //开单回调
                            placeOrderCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BILLING);
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
                        //对于包场订单未完成支付进行日订单支付
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
                            //包场回调
                            placeOrderCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);//认为是开单再支付
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
                            //门票回调
                            placeOrderCallbackService.ticketOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_TICKET);
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
                        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
                            //商品回调
                            placeOrderCallbackService.goodsOrderCompletePayOperate(reqOrderOperate);
                            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_GOODS);
                            placePrintVo.setIsMember(PlaceConstants.NO);
                        }
						if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
							//购物车回调
							placeOrderCallbackService.shoppingCartOrderCompletePayOperate(reqOrderOperate);
							placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
							placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_SHOPPING_CART);
							placePrintVo.setIsMember(PlaceConstants.NO);
						}
                    }
                    //会员充值业务
                    if (tbBizPlaceMemberOpHistory!=null&&tbBizPlaceMemberCard!=null){
                        reqOrderOperate.setOrderNo(tbBizPlaceMemberOpHistory.getOrderNo());
                        //tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                        placeOrderCallbackService.cardOrderCompletePayOperate(reqOrderOperate);
                        placePrintVo.setPlaceOrderId(tbBizPlaceMemberOpHistory.getOrderNo());
                        if (tbBizPlaceMemberOpHistory.getSrc().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN)){
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_OPEN_CARD);
                        }
                        if (tbBizPlaceMemberOpHistory.getSrc().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE)){
                            placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_RECHARGE_CARD);
                        }
                        placePrintVo.setIsMember(PlaceConstants.NO);
                    }
                    return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
                }else if(preOrderResponse.getData().getResult().equals(OrderStatusEnum.WAIT_BUYPER_PAY.getCode())){
                    //add start 银联pos支付返回条形码处理页面,获取pos条形码信息
					APIResponse<?> data = getUnionPosBarCodeInfo(placeScanOrderPayVo, reqScanPay, preOrderResponse);
					if (data != null) return data;
					//add end


					if (tbBizPlaceOrder != null){
                        return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY,tbBizPlaceOrder.getPlaceOrderId(),tbBizPlaceOrder.getPlaceOrderId());
                    }
                    if (tbBizPlacePrivateOrder != null){
                        return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY,tbBizPlacePrivateOrder.getPlaceOrderId(),tbBizPlacePrivateOrder.getPlaceOrderId());
                    }
                    if (tbBizPlaceMemberOpHistory!=null&&tbBizPlaceMemberCard!=null){
                        return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY,tbBizPlaceMemberOpHistory.getOrderNo(),tbBizPlaceMemberOpHistory.getOrderNo());
                    }

                }else{
                    logger.warn("订单系统返回：" + JSON.toJSONString(preOrderResponse));
                    return APIResponse.returnFail(preOrderResponse.getErrmsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail(e.getMessage());
        }
        return APIResponse.returnFail("查询不到该业务记录");
    }

	@Nullable
	private APIResponse<?> getUnionPosBarCodeInfo(PlaceScanOrderPayVo placeScanOrderPayVo, ReqScanPay reqScanPay, APIResponse<RespPreOrder> preOrderResponse) {
		if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(placeScanOrderPayVo.getAdminPayType().toString())) {
            Map<String,Object> data=new HashMap<>();
            data.put("orderNo",preOrderResponse.getData().getOrderNo());//支付中心订单号
            data.put("reqScanPay",reqScanPay.getAmount());//实付金额
            return APIResponse.returnSuccess(data);
        }
		return null;
	}

	@Override
	public List<TbBizPlaceOrder> getPlaceOrderList(ReqPlaceOrderSearchVo reqPlaceOrderSearchVo) {
		TbBizPlaceOrderExample example = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria criteria = example.createCriteria();
		criteria.andMobileEqualTo(reqPlaceOrderSearchVo.getMobile());
		criteria.andOrderStatusEqualTo(reqPlaceOrderSearchVo.getOrder_status());
		criteria.andUseTypeEqualTo(reqPlaceOrderSearchVo.getUseType());
		List<TbBizPlaceOrder> list = tbBizPlaceOrderMapper.selectByExample(example);
		return list;
	}

	@Override
	public TbBizPlaceOrder getOrderListByPlaceOrderId(String placeOrderId) {
		TbBizPlaceOrderExample example = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria criteria = example.createCriteria();
		criteria.andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlaceOrder> list = tbBizPlaceOrderMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}

	/** 判断订单是否是会员订单 **/
	@Override
	public APIResponse<?> isMemberOrderByPlaceOrderId(String placeOrderId) {
		String orderNo="";
		TbBizPlaceOrder tbBizPlaceOrder = getOrderListByPlaceOrderId(placeOrderId);
		if (tbBizPlaceOrder == null) {
			throw new BizException("此订单不存在");
		}
		
		TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
		com.quanyan.place.entity.TbBizPlaceMemberOpHistoryExample.Criteria criteria = tbBizPlaceMemberOpHistoryExample.createCriteria();
		//包场类型 
		if (PlaceConstants.ORDER_USE_BLOCK_BOOKING == tbBizPlaceOrder.getUseType()) {
			TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrder.getParentId());
			criteria.andOrderNoEqualTo(tbBizPlacePrivateOrder.getPlaceOrderId());
			orderNo=tbBizPlacePrivateOrder.getOrderNo();
		}else{
			criteria.andOrderNoEqualTo(placeOrderId);
			orderNo=tbBizPlaceOrder.getOrderNo();
		}
		
		List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = tbBizPlaceMemberOpHistoryMapper
				.selectByExample(tbBizPlaceMemberOpHistoryExample);
		RespMember respMember = new RespMember();
		
		//增加支付方式是否可变：0不改，1改
		if(StringUtils.isNoneEmpty(orderNo)){
			respMember.setIsChangePay(0);
		}else{
			respMember.setIsChangePay(1);
		}
		
		if (!CollectionUtils.isEmpty(tbBizPlaceMemberOpHistoryList)) {
			respMember.setMember(1);
			// 奇葩的需求
			if (tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo() != null) {
				TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
				tbBizPlaceMemberCardExample.createCriteria()
						.andInnerCardNoEqualTo(tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo());
				List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper
						.selectByExample(tbBizPlaceMemberCardExample);
				if (!CollectionUtils.isEmpty(tbBizPlaceMemberCardList)) {
					if (tbBizPlaceMemberCardList.get(0).getIsOldMember() != null) {
						if (tbBizPlaceMemberCardList.get(0).getIsOldMember() == 1) {
							respMember.setMember(2);
						}
					}
				}
			}
		} else {
			respMember.setMember(0);
		}
		return APIResponse.returnSuccess(respMember);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public APIResponse<?> saveBilling(ReqBillingInfo reqBillingInfo) throws Exception{

		BigDecimal receivedAmount = new BigDecimal(reqBillingInfo.getReceivedAmount());
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			return APIResponse.returnFail("场地id为空");
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			return APIResponse.returnFail("销售计划为空");
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//开单为0
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			return APIResponse.returnFail("订单明细为空");
		}
		BigDecimal price = new BigDecimal(0);
		//售卖总价格
		BigDecimal totalSalePrice = new BigDecimal(0);

		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			price = price.add(item.getSalePrice());
			totalSalePrice = totalSalePrice.add(item.getSalePrice());
		}
		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(receivedAmount,tbBizPlaceOrderItems,totalSalePrice);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
			tbBizPlaceOrderItemMapper.insertSelective(item);
		}
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setPaymentTime(new Date());
		tbBizPlaceOrder.setDebit(price);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_BILLING);
		tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
		tbBizPlaceOrder.setUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(price));
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
		tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
		if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getExpression())){
			tbBizPlaceOrder.setExpression(reqBillingInfo.getExpression());
		}else{
			tbBizPlaceOrder.setExpression("");
		}
		//普通支付
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);

		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
		if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
			logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
			tbBizPlacePayItem.setPlaceOrderId(orderid);
			tbBizPlacePayItem.setAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()));
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
			tbBizPlacePayItem.setPayType(reqBillingInfo.getAdminPayType());
			tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqBillingInfo.getAdminPayType()).getUnifiedId());
			if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) != 0) {
				//插入支付流水
				ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(tbBizPlaceOrder,new BigDecimal(reqBillingInfo.getReceivedAmount()),(byte)0,(byte)0);
				placeOrderUtilService.insertOrderHistory(reqOrderHistory);

				logger.debug("========================插入订单支付数据:TbBizPlacePayItem:{}",
						JSON.toJSONString(tbBizPlacePayItem));
				//iBaseService.placeBillingUpdatePlaceUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_ORDER_STATUS);
				placeBillingUpdatePlaceUnitSalePlanPlus(adjustTbBizPlaceOrderItems);
			}
		}
		PlacePrintVo placePrintVo = new PlacePrintVo();
		placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
		placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BILLING);
		placePrintVo.setIsMember(PlaceConstants.NO);
		return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
	}

	@Override
	public APIResponse<?> saveBillingForScanPay(ReqBillingInfo reqBillingInfo) throws Exception {

		BigDecimal receivedAmount = new BigDecimal(reqBillingInfo.getReceivedAmount());
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			return APIResponse.returnFail("场地id为空");
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			return APIResponse.returnFail("销售计划为空");
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE, reqBillingInfo, PlaceConstants.BILLING_TYPE);//开单为0
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			return APIResponse.returnFail("订单明细为空");
		}
		BigDecimal price = new BigDecimal(0);
		//售卖总价格
		BigDecimal totalSalePrice = new BigDecimal(0);

		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			price = price.add(item.getSalePrice());
			totalSalePrice = totalSalePrice.add(item.getSalePrice());
		}
		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(receivedAmount, tbBizPlaceOrderItems, totalSalePrice);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems) {
			tbBizPlaceOrderItemMapper.insertSelective(item);
		}
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客" : reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setPaymentTime(null);
		tbBizPlaceOrder.setDebit(price);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_BILLING);
		tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
		tbBizPlaceOrder.setUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(price));
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
		tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
		if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getExpression())) {
			tbBizPlaceOrder.setExpression(reqBillingInfo.getExpression());
		} else {
			tbBizPlaceOrder.setExpression("");
		}

		//扫码支付
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.NOT_PAY_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.ORDER_PREPAY_STATUS);

		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqBillingInfo.getAdminPayType().toString())){
			tbBizPlaceOrder.setIsType(PlaceConstants.YES);
		}
		if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
			logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
			 if (!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqBillingInfo.getAdminPayType().toString())){//非pos直接生成支付明细
				 TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
					tbBizPlacePayItem.setPlaceOrderId(orderid);
					tbBizPlacePayItem.setAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()));
					tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
					tbBizPlacePayItem.setPayType(reqBillingInfo.getAdminPayType());
					tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqBillingInfo.getAdminPayType()).getUnifiedId());
					if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) != 0) {
						logger.debug("========================插入订单支付数据:TbBizPlacePayItem:{}",
								JSON.toJSONString(tbBizPlacePayItem));
						iBaseService.placeBillingUpdatePlaceUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_LOCk_STATUS);
					}
			 }else{//支付成功生成支付明细pos
				//锁场
					iBaseService.placeBillingUpdatePlaceUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_LOCk_STATUS);
			 }
			
			
			
			
		}

		return APIResponse.returnSuccess(tbBizPlaceOrder);
//        return APIResponse.returnSuccess(PlaceErrorCodeEnum.ORDER_WAIT_PAY,orderid);
//        if (PlaceConstants.NOT_PAY_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
//                || PlaceConstants.ORDER_PREPAY_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
//            placeBillingUpdatePlaceUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_LOCk_STATUS);
//            return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY,orderid,orderid);
//        }else{
//            placeBillingUpdatePlaceUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_ORDER_STATUS);
//            return APIResponse.returnSuccess(PlaceErrorCodeEnum.ORDER_SUCCESS_PAY);
//        }
	}

	/**
	 * 会员开单
	 * @param reqBillingInfo
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public APIResponse<?> saveBillingForMemberPlus(ReqBillingInfo reqBillingInfo) throws Exception{
		BigDecimal receivedAmount = new BigDecimal(reqBillingInfo.getReceivedAmount());
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			return APIResponse.returnFail("unitids参数错误");
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			return APIResponse.returnFail("销售计划为空");
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//会员价
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			return APIResponse.returnFail("生成订单明细为空");
		}
		BigDecimal price = new BigDecimal(0);
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsPrice = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//普通价
		BigDecimal notMemberPrice = new BigDecimal(0);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsPrice){
			notMemberPrice = notMemberPrice.add(item.getSalePrice());
		}
		TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
		//判断销售计划是否在会员卡优惠时段范围内
		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans){
			boolean flag1 = DateUtils.dateCompare(tbBizPlaceUnitSalePlan.getStartTime(),tbBizPlaceMemberCard.getAvailableStartTime(),true);//销售计划开始时间>=会员卡优惠开始时间返回true
			boolean flag2 = DateUtils.dateCompare(tbBizPlaceMemberCard.getAvailableEndTime(),tbBizPlaceUnitSalePlan.getEndTime(),true);//会员卡优惠结束时间>=销售计划结束时间返回true
			if (!(flag1 && flag2)){
				return APIResponse.returnFail("您选择的会员卡仅支持"+DateTimeUtils.convertDate2String("HH:mm:ss",
						tbBizPlaceMemberCard.getAvailableStartTime())+"-"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableEndTime())+
						"时间段的场馆费用支付");
			}
		}

		//折后价格
		BigDecimal countPrice = new BigDecimal(0);
		//售卖总价格
		BigDecimal totalSalePrice = new BigDecimal(0);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard)){
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
					//取折扣
					BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
					//打折扣
					countPrice = countPrice.add(item.getSalePrice().multiply(discount.divide(new BigDecimal(100))));
				}else {
					countPrice = countPrice.add(item.getSalePrice());
				}
			}
			price = price.add(item.getSalePrice());
			totalSalePrice = totalSalePrice.add(item.getSalePrice());
		}
		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(receivedAmount,tbBizPlaceOrderItems,totalSalePrice);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
			tbBizPlaceOrderItemMapper.insertSelective(item);
		}
		//获取会员卡
		if(!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getMemberCardId())){
			BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
			BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
			BigDecimal zeroAmount = new BigDecimal(0);
			if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE){//储值卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							return APIResponse.returnFail("请充值会员卡！");
						}
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT){//折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
					}
					else{
						return APIResponse.returnFail("请充值会员卡！");
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT){//储值折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receivedAmount));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							return APIResponse.returnFail("请充值会员卡！");
						}
					}
				}
			}
			tbBizPlaceMemberCard.setUpdateTime(new Date());
			int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
			if (flag1 ==1 ){
				logger.debug("-------------------会员开单会员卡余额更新完毕-------------");
				//Todo 打折日志记录    折扣前会员价，折扣后价格
				TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
				tbBizPlaceMemberOpHistory.setCreateUid(reqBillingInfo.getCreateUid());
				tbBizPlaceMemberOpHistory.setPlaceId(reqBillingInfo.getPlaceId());
				tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
				tbBizPlaceMemberOpHistory.setAmount(receivedAmount);
				tbBizPlaceMemberOpHistory.setCreateTime(new Date());
				tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
				//TODO 生成流水号
				tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqBillingInfo.getPlaceId()));
				tbBizPlaceMemberOpHistory.setOrderNo(orderid);
				tbBizPlaceMemberOpHistory.setOpTypeName("商家端-"+iBaseService.getCommonDataCache("cagetory" + reqBillingInfo.getCategoryId().toString())+"场地费用");
				if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getContactInformation()) && !org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName())){
					Integer uid = placeMemberService.getUidByNameAndPhone(reqBillingInfo.getName(),reqBillingInfo.getContactInformation());
					tbBizPlaceMemberOpHistory.setUid(uid);
				}else{
					throw new Exception("参数错误！");
				}
				tbBizPlaceMemberOpHistory.setUserName(reqBillingInfo.getName());
				tbBizPlaceMemberOpHistory.setMobile(reqBillingInfo.getContactInformation());
				TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqBillingInfo.getMemberCardId());
				tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
				tbBizPlaceMemberOpHistory.setMemo(reqBillingInfo.getMemo());
				tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
				tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
				tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
				tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
				tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
				tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
				tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
				tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
				tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());
				tbBizPlaceMemberOpHistory.setPayType(reqBillingInfo.getAdminPayType());
				tbBizPlaceMemberOpHistory.setPlatform(5);//后台开单
				int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
				if (flag2 ==1 ) {
					logger.debug("-------------------会员开单操作记录完毕-------------");
				}
			}
		}
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
		tbBizPlaceOrder.setPaymentTime(new Date());
		tbBizPlaceOrder.setDebit(notMemberPrice);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setUid(placeMemberService.getUidByNameAndPhone(null,reqBillingInfo.getContactInformation()));
		tbBizPlaceOrder.setHandAdjustAmount(countPrice.equals(new BigDecimal(0))?new BigDecimal(0):new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(countPrice));
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
		tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
		tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
		if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getExpression())){
			tbBizPlaceOrder.setExpression(reqBillingInfo.getExpression());
		}else{
			tbBizPlaceOrder.setExpression("");
		}

		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
			logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
			TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
			tbBizPlacePayItem.setPlaceOrderId(orderid);
			tbBizPlacePayItem.setAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()));
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
			tbBizPlacePayItem.setPayType(reqBillingInfo.getAdminPayType());
			tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqBillingInfo.getAdminPayType()).getUnifiedId());
			if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) != 0) {
				//插入支付流水
				ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(tbBizPlaceOrder,new BigDecimal(reqBillingInfo.getReceivedAmount()),(byte)0,(byte)0);
				placeOrderUtilService.insertOrderHistory(reqOrderHistory);

				//修改销售计划状态为已售
				placeBillingUpdatePlaceUnitSalePlanPlus(adjustTbBizPlaceOrderItems);

				TbBizPlace place=placeBaseService.getPlaceById(reqBillingInfo.getPlaceId());
				List<String> mobileList=new ArrayList<>();
				List<String> paramList=new ArrayList<>();

				//成功消费发送短信提醒
				String [] args=new String[7];
				args[0] = place != null ? place.getName() : "";
				args[1] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getCardName() : "";
				args[2] = DateUtils.getCurrentTime();
				args[3] ="场地预定";
				args[4] = receivedAmount != null ? receivedAmount.toString()+"元":"";
				args[5]=tbBizPlaceMemberCard!=null?tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).toString()+"元":"";
				// 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
				TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(reqBillingInfo.getPlaceId());
				if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
					args[6]=placeAttach.getBookingConsultPhone();
				} else {
					// 获取系统配置的百灵鸟客服热线
					TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
					args[6]=parameterVo!=null?parameterVo.getParameterValue():"";
				}

				mobileList.add(reqBillingInfo.getContactInformation());
				paramList.addAll(Arrays.asList(args));
				try{
					//placeTicketService.asyncSendSms(reqBillingInfo.getContactInformation(), SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE,args,true);
					placeSmsService.sendSms(mobileList, SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
				}catch(Exception e){
					logger.info("短信发送失败-------->"+e.getMessage());
				}
			}
		}
		PlacePrintVo placePrintVo = new PlacePrintVo();
		placePrintVo.setIsMember(PlaceConstants.YES);
		placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BILLING);
		placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
		return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
	}

	/**
	 * 会员开单
	 * @param reqBillingInfo
	 * @return
	 */
	@Override
	public APIResponse<?> saveBillingForMember(ReqBillingInfo reqBillingInfo) throws Exception{
		BigDecimal receivedAmount = new BigDecimal(reqBillingInfo.getReceivedAmount());
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			throw new Exception("unitIds is null");
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			throw new Exception("PlaceUnitSalePlans is null");
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//会员价
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			throw new Exception("PlaceOrderItems is null");
		}
		BigDecimal price = new BigDecimal(0);
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsPrice = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//普通价
		BigDecimal notMemberPrice = new BigDecimal(0);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsPrice){
			notMemberPrice = notMemberPrice.add(item.getSalePrice());
		}
		TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
		//判断销售计划是否在会员卡优惠时段范围内
		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans){
//            tbBizPlaceMemberCard.getAvailableStartTime();
//            tbBizPlaceMemberCard.getAvailableEndTime();
//            tbBizPlaceUnitSalePlan.getStartTime();
//            tbBizPlaceUnitSalePlan.getEndTime();
			boolean flag1 = DateUtils.dateCompare(tbBizPlaceUnitSalePlan.getStartTime(),tbBizPlaceMemberCard.getAvailableStartTime(),true);//销售计划开始时间>=会员卡优惠开始时间返回true
			boolean flag2 = DateUtils.dateCompare(tbBizPlaceMemberCard.getAvailableEndTime(),tbBizPlaceUnitSalePlan.getEndTime(),true);//会员卡优惠结束时间>=销售计划结束时间返回true
			if (!(flag1 && flag2)){
				throw new Exception("您选择的会员卡仅支持"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableStartTime())+"-"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableEndTime())+"时间段的场馆费用支付");
			}
		}

		//折后价格
		BigDecimal countPrice = new BigDecimal(0);
		//售卖总价格
		BigDecimal totalSalePrice = new BigDecimal(0);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard)){
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
					//取折扣
					BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
					//打折扣
					countPrice = countPrice.add(item.getSalePrice().multiply(discount.divide(new BigDecimal(100))));
				}else {
					countPrice = countPrice.add(item.getSalePrice());
				}
			}
			price = price.add(item.getSalePrice());
			totalSalePrice = totalSalePrice.add(item.getSalePrice());
		}
		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(receivedAmount,tbBizPlaceOrderItems,totalSalePrice);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
			tbBizPlaceOrderItemMapper.insertSelective(item);
		}
		//获取会员卡
		if(!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getMemberCardId())){
			BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
			BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
			BigDecimal zeroAmount = new BigDecimal(0);
			if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE){//储值卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("请充值会员卡！");
						}
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT){//折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
					}
                    /*else{
                        //会员卡上的本金+赠送金额大于等于消费金额
                        if (tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getGiveAmount()).doubleValue() >= price.doubleValue()){
                            tbBizPlaceMemberCard.setSurplusAmount(new BigDecimal(0));
                            tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().subtract(price.subtract(tbBizPlaceMemberCard.getSurplusAmount())));
                        }else{
                            return APIResponse.returnFail("请充值会员卡！");
                        }
                    }*/
					else{
						throw new Exception("请充值会员卡！");
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT){//储值折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receivedAmount));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("请充值会员卡！");
						}
					}
				}
			}
			tbBizPlaceMemberCard.setUpdateTime(new Date());
			int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
			if (flag1 ==1 ){
				logger.debug("-------------------会员开单会员卡余额更新完毕-------------");
				//Todo 打折日志记录    折扣前会员价，折扣后价格
				TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
				tbBizPlaceMemberOpHistory.setCreateUid(reqBillingInfo.getCreateUid());
				tbBizPlaceMemberOpHistory.setPlaceId(reqBillingInfo.getPlaceId());
				tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
				tbBizPlaceMemberOpHistory.setAmount(receivedAmount);
				tbBizPlaceMemberOpHistory.setCreateTime(new Date());
				tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
				//TODO 生成流水号
				tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqBillingInfo.getPlaceId()));
				tbBizPlaceMemberOpHistory.setOrderNo(orderid);
				tbBizPlaceMemberOpHistory.setOpTypeName("商家端-"+iBaseService.getCommonDataCache("cagetory" + reqBillingInfo.getCategoryId().toString())+"场地费用");
				if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getContactInformation()) && !org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName())){
					Integer uid = placeMemberService.getUidByNameAndPhone(reqBillingInfo.getName(),reqBillingInfo.getContactInformation());
					tbBizPlaceMemberOpHistory.setUid(uid);
				}else{
					throw new Exception("参数错误！");
				}
				tbBizPlaceMemberOpHistory.setUserName(reqBillingInfo.getName());
				tbBizPlaceMemberOpHistory.setMobile(reqBillingInfo.getContactInformation());
				TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqBillingInfo.getMemberCardId());
				tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
				tbBizPlaceMemberOpHistory.setMemo(reqBillingInfo.getMemo());
				tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
				tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
				tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
				tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
				tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
				tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
				tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
				tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
				tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());
				tbBizPlaceMemberOpHistory.setPayType(reqBillingInfo.getAdminPayType());
				tbBizPlaceMemberOpHistory.setPlatform(5);//后台开单
				int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
				if (flag2 ==1 ) {
					logger.debug("-------------------会员开单操作记录完毕-------------");
				}
			}
		}
		System.out.println("打折后价格------------------------------------"+countPrice);
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
		tbBizPlaceOrder.setPaymentTime(new Date());
		tbBizPlaceOrder.setDebit(notMemberPrice);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setUid(placeMemberService.getUidByNameAndPhone(null,reqBillingInfo.getContactInformation()));
		tbBizPlaceOrder.setHandAdjustAmount(countPrice.equals(new BigDecimal(0))?new BigDecimal(0):new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(countPrice));
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
		tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
		tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
		if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getExpression())){
			tbBizPlaceOrder.setExpression(reqBillingInfo.getExpression());
		}else{
			tbBizPlaceOrder.setExpression("");
		}

		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
			logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
			TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
			tbBizPlacePayItem.setPlaceOrderId(orderid);
			tbBizPlacePayItem.setAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()));
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
			tbBizPlacePayItem.setPayType(reqBillingInfo.getAdminPayType());
			tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqBillingInfo.getAdminPayType()).getUnifiedId());
			if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) != 0) {
				//插入支付流水
				ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(tbBizPlaceOrder,new BigDecimal(reqBillingInfo.getReceivedAmount()),(byte)0,(byte)0);
				placeOrderUtilService.insertOrderHistory(reqOrderHistory);

				logger.debug("========================插入订单支付数据:TbBizPlacePayItem:{}",
						JSON.toJSONString(tbBizPlacePayItem));
				//修改销售计划
				List<UnitSalePlan> list = new ArrayList<>();
				for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
					UnitSalePlan up = new UnitSalePlan();
					up.setSaleId(tsp.getSaleId());
					list.add(up);
				}
				ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
				reqPlaceOrderListVo.setUnitSalePlanIdList(list);
				reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
				int flag = iBaseService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);
				logger.debug("========================修改销售计划数据:ReqPlaceOrderListVo:{}",
						JSON.toJSONString(reqPlaceOrderListVo));
				if (flag>0){
					TbBizPlace place=placeBaseService.getPlaceById(reqBillingInfo.getPlaceId());
					List<String> mobileList=new ArrayList<>();
					List<String> paramList=new ArrayList<>();

					//成功消费发送短信提醒
					String [] args=new String[7];
					args[0] = place != null ? place.getName() : "";
					args[1] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getCardName() : "";
					args[2] = DateUtils.getCurrentTime();
					args[3] ="场地预定";
					args[4] = receivedAmount != null ? receivedAmount.toString()+"元":"";
					args[5]=tbBizPlaceMemberCard!=null?tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).toString()+"元":"";
					// 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
					TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(reqBillingInfo.getPlaceId());
					if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
						args[6]=placeAttach.getBookingConsultPhone();
					} else {
						// 获取系统配置的百灵鸟客服热线
						TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
						args[6]=parameterVo!=null?parameterVo.getParameterValue():"";
					}

					mobileList.add(reqBillingInfo.getContactInformation());
					paramList.addAll(Arrays.asList(args));
					try{
						//placeTicketService.asyncSendSms(reqBillingInfo.getContactInformation(), SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE,args,true);
						placeSmsService.sendSms(mobileList, SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
					}catch(Exception e){
						logger.info("短信发送失败-------->"+e.getMessage());
					}
					PlacePrintVo placePrintVo = new PlacePrintVo();
					placePrintVo.setIsMember(PlaceConstants.YES);
					placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BILLING);
					placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
					return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
				}
			}
		}
		return APIResponse.returnFail("会员订场失败");
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean saveBookForMember(ReqBillingInfo reqBillingInfo) throws Exception{
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			return false;
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			return false;
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//拿会员价
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			return false;
		}
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsPrice = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//普通价
		BigDecimal notMemberPrice = new BigDecimal(0);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsPrice){
			notMemberPrice = notMemberPrice.add(item.getSalePrice());
		}
		BigDecimal price = new BigDecimal(0);

		TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
		//判断销售计划是否在会员卡优惠时段范围内
		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans){
//            tbBizPlaceMemberCard.getAvailableStartTime();
//            tbBizPlaceMemberCard.getAvailableEndTime();
//            tbBizPlaceUnitSalePlan.getStartTime();
//            tbBizPlaceUnitSalePlan.getEndTime();
			boolean flag1 = DateUtils.dateCompare(tbBizPlaceUnitSalePlan.getStartTime(),tbBizPlaceMemberCard.getAvailableStartTime(),true);//销售计划开始时间>=会员卡优惠开始时间返回true
			boolean flag2 = DateUtils.dateCompare(tbBizPlaceMemberCard.getAvailableEndTime(),tbBizPlaceUnitSalePlan.getEndTime(),true);//会员卡优惠结束时间>=销售计划结束时间返回true
			if (!(flag1 && flag2)){
				throw new Exception("您选择的会员卡仅支持"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableStartTime())+"-"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableEndTime())+"时间段的场馆费用支付");
			}
		}
		BigDecimal hundredAmount = new BigDecimal(100);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			//插入明细
			if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard)){
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
					//取折扣
					BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
					//打折扣
					item.setSalePrice(item.getSalePrice().multiply(discount.divide(hundredAmount)));
					iBaseService.saveTbBizpPlaceOrderItem(item);
				}else{
					iBaseService.saveTbBizpPlaceOrderItem(item);
				}
			}else{
				iBaseService.saveTbBizpPlaceOrderItem(item);
			}
			logger.debug("===================插入明细数据:TbBizPlaceOrderItem:{}", JSON.toJSONString(item));
			price = price.add(item.getSalePrice());
		}
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
		tbBizPlaceOrder.setDebit(notMemberPrice);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());

		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
		tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());

		if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
			logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
			//修改销售计划
			List<UnitSalePlan> list = new ArrayList<>();
			for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
				UnitSalePlan up = new UnitSalePlan();
				up.setSaleId(tsp.getSaleId());
				list.add(up);
			}
			ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
			reqPlaceOrderListVo.setUnitSalePlanIdList(list);
			reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_LOCk_STATUS);
			//int flag = placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
			int flag = iBaseService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);
			logger.debug("========================修改销售计划数据:ReqPlaceOrderListVo:{}",
					JSON.toJSONString(reqPlaceOrderListVo));
			if (flag !=0 ) {
				BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
				BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
				TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
				tbBizPlaceMemberOpHistory.setCreateUid(reqBillingInfo.getCreateUid());
				tbBizPlaceMemberOpHistory.setPlaceId(reqBillingInfo.getPlaceId());
				tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
				tbBizPlaceMemberOpHistory.setAmount(price);
				tbBizPlaceMemberOpHistory.setCreateTime(new Date());
				tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());

				tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqBillingInfo.getPlaceId()));
				tbBizPlaceMemberOpHistory.setOrderNo(orderid);
				tbBizPlaceMemberOpHistory.setOpTypeName("线下-" + iBaseService.getCommonDataCache("cagetory" + reqBillingInfo.getCategoryId().toString()) + "场地开单预订");
				if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getContactInformation()) && !org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName())) {
					Integer uid = placeMemberService.getUidByNameAndPhone(reqBillingInfo.getName(), reqBillingInfo.getContactInformation());
					tbBizPlaceMemberOpHistory.setUid(uid);
				}
				tbBizPlaceMemberOpHistory.setUserName(reqBillingInfo.getName());
				tbBizPlaceMemberOpHistory.setMobile(reqBillingInfo.getContactInformation());
				TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqBillingInfo.getMemberCardId());
				tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
				tbBizPlaceMemberOpHistory.setMemo(reqBillingInfo.getMemo());
				tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
				tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
				tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);//预订流水记录无效
				tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
				tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
				tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
				tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
				tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
				tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());

				tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
			}
			return flag != 0;
		}
		return false;
	}

	@Override
	public APIResponse<?> saveBookForMemberPlus(ReqBillingInfo reqBillingInfo) throws Exception{
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			return APIResponse.returnFail("unitids参数错误");
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			return APIResponse.returnFail("销售计划为空");
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//拿会员价
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			return APIResponse.returnFail("生成订单明细为空");
		}
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsPrice = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//普通价
		BigDecimal notMemberPrice = new BigDecimal(0);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsPrice){
			notMemberPrice = notMemberPrice.add(item.getSalePrice());
		}
		BigDecimal price = new BigDecimal(0);

		TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
		//判断销售计划是否在会员卡优惠时段范围内
		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans){
//            tbBizPlaceMemberCard.getAvailableStartTime();
//            tbBizPlaceMemberCard.getAvailableEndTime();
//            tbBizPlaceUnitSalePlan.getStartTime();
//            tbBizPlaceUnitSalePlan.getEndTime();
			boolean flag1 = DateUtils.dateCompare(tbBizPlaceUnitSalePlan.getStartTime(),tbBizPlaceMemberCard.getAvailableStartTime(),true);//销售计划开始时间>=会员卡优惠开始时间返回true
			boolean flag2 = DateUtils.dateCompare(tbBizPlaceMemberCard.getAvailableEndTime(),tbBizPlaceUnitSalePlan.getEndTime(),true);//会员卡优惠结束时间>=销售计划结束时间返回true
			if (!(flag1 && flag2)){
				throw new Exception("您选择的会员卡仅支持"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableStartTime())+"-"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableEndTime())+"时间段的场馆费用支付");
			}
		}
		BigDecimal hundredAmount = new BigDecimal(100);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			//插入明细
			if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard)){
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
					//取折扣
					BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
					//打折扣
					item.setSalePrice(item.getSalePrice().multiply(discount.divide(hundredAmount)));
					iBaseService.saveTbBizpPlaceOrderItem(item);
				}else{
					iBaseService.saveTbBizpPlaceOrderItem(item);
				}
			}else{
				iBaseService.saveTbBizpPlaceOrderItem(item);
			}
			logger.debug("===================插入明细数据:TbBizPlaceOrderItem:{}", JSON.toJSONString(item));
			price = price.add(item.getSalePrice());
		}
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
		tbBizPlaceOrder.setDebit(notMemberPrice);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());

		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
		tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());

		if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {

			BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
			BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
			TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
			tbBizPlaceMemberOpHistory.setCreateUid(reqBillingInfo.getCreateUid());
			tbBizPlaceMemberOpHistory.setPlaceId(reqBillingInfo.getPlaceId());
			tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
			tbBizPlaceMemberOpHistory.setAmount(price);
			tbBizPlaceMemberOpHistory.setCreateTime(new Date());
			tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());

			tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqBillingInfo.getPlaceId()));
			tbBizPlaceMemberOpHistory.setOrderNo(orderid);
			tbBizPlaceMemberOpHistory.setOpTypeName("线下-" + iBaseService.getCommonDataCache("cagetory" + reqBillingInfo.getCategoryId().toString()) + "场地开单预订");
			if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getContactInformation()) && !org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName())) {
				Integer uid = placeMemberService.getUidByNameAndPhone(reqBillingInfo.getName(), reqBillingInfo.getContactInformation());
				tbBizPlaceMemberOpHistory.setUid(uid);
			}
			tbBizPlaceMemberOpHistory.setUserName(reqBillingInfo.getName());
			tbBizPlaceMemberOpHistory.setMobile(reqBillingInfo.getContactInformation());
			TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqBillingInfo.getMemberCardId());
			tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
			tbBizPlaceMemberOpHistory.setMemo(reqBillingInfo.getMemo());
			tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
			tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
			tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);//预订流水记录无效
			tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
			tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
			tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
			tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
			tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
			tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());

			tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);

		}
		return APIResponse.returnSuccess();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean saveBook(ReqBillingInfo reqBillingInfo) {
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			return false;
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			return false;
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//开单为0
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			return false;
		}
		BigDecimal price = new BigDecimal(0);

		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			//插入明细
			iBaseService.saveTbBizpPlaceOrderItem(item);
			logger.debug("===================插入明细数据:TbBizPlaceOrderItem:{}", JSON.toJSONString(item));
			price = price.add(item.getSalePrice());
		}
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
		tbBizPlaceOrder.setDebit(price);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		tbBizPlaceOrder.setIsMember(PlaceConstants.NO);

		if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
			logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
			//修改销售计划
			List<UnitSalePlan> list = new ArrayList<>();
			for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
				UnitSalePlan up = new UnitSalePlan();
				up.setSaleId(tsp.getSaleId());
				list.add(up);
			}
			ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
			reqPlaceOrderListVo.setUnitSalePlanIdList(list);
			reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_LOCk_STATUS);
			//int flag = placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
			int flag = iBaseService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);
			logger.debug("========================修改销售计划数据:ReqPlaceOrderListVo:{}",
					JSON.toJSONString(reqPlaceOrderListVo));
			return flag != 0;
		}
		return false;
	}

	@Override
	public APIResponse<?> saveBookPlus(ReqBillingInfo reqBillingInfo) throws Exception{
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
		if (org.springframework.util.StringUtils.isEmpty(unitids) && unitids.length > 0) {
			return APIResponse.returnFail("unitids参数错误");
		}
		List unitidss = new ArrayList();
		for (int i = 0, len = unitids.length; i < len; i++) {
			unitidss.add(unitids[i]);
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(unitidss);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
			return APIResponse.returnFail("销售计划为空");
		}
		String orderid = iBaseService.getBizOrderId(reqBillingInfo.getCreateUid());
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = iBaseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
				reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.BILLING_TYPE);//开单为0
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
			return APIResponse.returnFail("生成订单明细失败");
		}
		BigDecimal price = new BigDecimal(0);

		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			//插入明细
			iBaseService.saveTbBizpPlaceOrderItem(item);
			price = price.add(item.getSalePrice());
		}
		//插入订单
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

		tbBizPlaceOrder.setPlaceOrderId(orderid);
		tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
		tbBizPlaceOrder.setCustomerName(org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
		tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
		tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
		tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setUid(reqBillingInfo.getCreateUid());
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
		tbBizPlaceOrder.setDebit(price);
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setEndTime(new Date());
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

		tbBizPlaceOrder.setIsMember(PlaceConstants.NO);

		tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder);

		return APIResponse.returnSuccess();
	}

	@Override
	public boolean cancelBook(String reqPlaceOrderId) throws Exception {
		//查询订单
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		if(!com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrders)){
			for(TbBizPlaceOrder tbBizPlaceOrder : tbBizPlaceOrders){
				//防止重复取消
				if (tbBizPlaceOrder.getOrderStatus().intValue() != 1){
					throw new Exception("当前订单状态不支持取消");
				}

				TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
				org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrder, newTbBizPlaceOrder);
				//修改取消订单状态
				newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
				newTbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
				newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
				newTbBizPlaceOrder.setEndTime(new Date());

				TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
				TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
				tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(newTbBizPlaceOrder.getPlaceOrderId());
				tbBizPlaceOrderCriteria1.andOrderStatusEqualTo(PlaceConstants.ORDER_PREPAY_STATUS);
				tbBizPlaceOrderCriteria1.andPayStatusEqualTo(PlaceConstants.NOT_PAY_STATUS);
				TbBizPlaceOrder updateTbBizPlaceOrder = new TbBizPlaceOrder();
				BeanUtils.copyProperties(newTbBizPlaceOrder,updateTbBizPlaceOrder);
				updateTbBizPlaceOrder.setId(null);//防止主键冲突
				if(this.tbBizPlaceOrderMapper.updateByExampleSelective(updateTbBizPlaceOrder,tbBizPlaceOrderExample1) != 0){
					
					//根据placeOrderId拿到placeOrderItem
					TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
					itemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
					List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
					if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
						return false;
					}
					// 释放库存
					refundUpdateUnitSalePlan(tbBizPlaceOrderItems, PlaceConstants.PLACE_PREORDER_STATUS);
					//会员取消预订
					TbBizPlaceMemberOpHistoryExample example = new TbBizPlaceMemberOpHistoryExample();
					TbBizPlaceMemberOpHistoryExample.Criteria criteria = example.createCriteria();
					criteria.andOrderNoEqualTo(reqPlaceOrderId);
					
					List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example);
					if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)){
						String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
						if(!org.springframework.util.StringUtils.isEmpty(innerCardNo)){
							TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
							TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
							tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo);
							List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
							if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList) ){
								TbBizPlaceMemberCard tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
								BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
								BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
								TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
								
								tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
								tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
								tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
								tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
								tbBizPlaceMemberOpHistory.setAmount(new BigDecimal(0));
								tbBizPlaceMemberOpHistory.setCreateTime(new Date());
								tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
								tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
								tbBizPlaceMemberOpHistory.setOrderNo(reqPlaceOrderId);
								tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName()+"取消");
								tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
								tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
								tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
								tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
								tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList.get(0).getMemo());
								tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
								tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
								tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
								tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
								tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
								tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
								tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
								tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
								tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());
								tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKeySelective(tbBizPlaceMemberOpHistory);
							}
						}
					}
					//释放场地状态更新场地价格
					try {
						placeInnerService.syncSalePlanPriceForRefundOrder(tbBizPlaceOrder.getPlaceOrderId());
					} catch (Exception e) {
						e.printStackTrace();
					}
					return true;
				}
				return false;
			}
		}
		return false;
	}
	
	@Override
	public boolean cancelBlockBook(String reqPlaceOrderId) {
		//查询订单
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		if(!com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrders)){
			for(TbBizPlaceOrder tbBizPlaceOrder : tbBizPlaceOrders){
				TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
				org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrder, newTbBizPlaceOrder);
				//修改取消订单状态
				newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
				newTbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
				newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
				newTbBizPlaceOrder.setEndTime(new Date());

				TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
				TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
				tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(newTbBizPlaceOrder.getPlaceOrderId());
				tbBizPlaceOrderCriteria1.andOrderStatusEqualTo(PlaceConstants.ORDER_PREPAY_STATUS);
				tbBizPlaceOrderCriteria1.andPayStatusEqualTo(PlaceConstants.NOT_PAY_STATUS);
				TbBizPlaceOrder updateTbBizPlaceOrder = new TbBizPlaceOrder();
				BeanUtils.copyProperties(newTbBizPlaceOrder,updateTbBizPlaceOrder);
				updateTbBizPlaceOrder.setId(null);//防止主键冲突
				if(this.tbBizPlaceOrderMapper.updateByExampleSelective(updateTbBizPlaceOrder,tbBizPlaceOrderExample1) != 0){
					
					//根据placeOrderId拿到placeOrderItem
					TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
					itemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
					List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
					if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
						return false;
					}
					// 释放库存
					try {
						refundUpdateUnitSalePlan(tbBizPlaceOrderItems, PlaceConstants.PLACE_PREORDER_STATUS);
					} catch (Exception e){
						e.printStackTrace();
						return false;
					}
					//会员取消预订
					TbBizPlaceMemberOpHistoryExample example = new TbBizPlaceMemberOpHistoryExample();
					TbBizPlaceMemberOpHistoryExample.Criteria criteria = example.createCriteria();
					
					if (PlaceConstants.ORDER_USE_BLOCK_BOOKING == tbBizPlaceOrder.getUseType()){
						TbBizPlacePrivateOrder tbBizPlacePrivateOrder = 
								tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrder.getParentId());
						criteria.andOrderNoEqualTo(tbBizPlacePrivateOrder.getPlaceOrderId());
								
					}else {
						criteria.andOrderNoEqualTo(reqPlaceOrderId);
					}
					
					List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example);
					if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)){
						String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
						if(!org.springframework.util.StringUtils.isEmpty(innerCardNo)){
							TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
							TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
							tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo);
							List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
							if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList) ){
								TbBizPlaceMemberCard tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
								BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
								BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
								TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
								
								tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
								tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
								tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
								tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
								tbBizPlaceMemberOpHistory.setAmount(new BigDecimal(0));
								tbBizPlaceMemberOpHistory.setCreateTime(new Date());
								tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
								tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
								tbBizPlaceMemberOpHistory.setOrderNo(reqPlaceOrderId);
								tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName()+"取消");
								tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
								tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
								tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
								tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
								tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList.get(0).getMemo());
								tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
								tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
								tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
								tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
								tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
								tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
								tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
								tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
								tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());

								if (PlaceConstants.ORDER_USE_BLOCK_BOOKING == tbBizPlaceOrder.getUseType()){
									tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
									//更新父订单状态
									checkBlockOrder(tbBizPlaceOrder, PlaceConstants.ORDER_CLOSE_STATUS ,null);
									
								}else {
									tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKeySelective(tbBizPlaceMemberOpHistory);
								}
								
							}
						}
					}
					//释放场地状态更新场地价格
					try {
						placeInnerService.syncSalePlanPriceForRefundOrder(tbBizPlaceOrder.getPlaceOrderId());
					} catch (Exception e) {
						e.printStackTrace();
					}
					return true;
				}
				return false;
			}
		}
		return false;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public APIResponse savePay(String reqPlaceOrderId,Integer adminPayType, String receivedAmount,String memo,String expression) throws Exception {
		BigDecimal receivedAmount1 = new BigDecimal(receivedAmount);
		//查询订单
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);

		//是否会员
		boolean isMember = false;

		if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrders)){
			throw new Exception("没有对应的订单");
		}
		if(tbBizPlaceOrders.size() > 1){
			throw new Exception("订单异常，有重复订单");
		}
		TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrders.get(0);
		if (tbBizPlaceOrder.getOrderStatus() > 1){
			return APIResponse.returnFail("订单状态已更新,无法支付！");
		}
		//判断是否审核通过  审核中，审核通过不能再付款

		//if ()

		//支付明细
		TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
		tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
		boolean payItemFlag = false;
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlacePayItemList)){
			payItemFlag = true;
		}

		//订单明细
		//根据placeOrderId拿到placeOrderItem
		TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
		itemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
			throw new Exception("订单明细为null");
		}
		BigDecimal price = new BigDecimal(0);
		List<Integer> unitIds = new ArrayList<>();
		//拿到销售计划场地Id
		for(TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			unitIds.add(tbBizPlaceOrderItem.getUnitSalePlanId());
			price = price.add(tbBizPlaceOrderItem.getSalePrice());
		}
		List<TbBizPlaceOrderItem> newTbBizPlaceOrderItemList = new ArrayList<TbBizPlaceOrderItem>();
		org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrderItems,newTbBizPlaceOrderItemList);

		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(receivedAmount1,tbBizPlaceOrderItems,price);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
			tbBizPlaceOrderItemMapper.updateByPrimaryKeySelective(item);
		}

		//修改订单
		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
		org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrder,newTbBizPlaceOrder);
		//修改取消订单状态
		newTbBizPlaceOrder.setId(tbBizPlaceOrder.getId());
		newTbBizPlaceOrder.setPlaceOrderId(reqPlaceOrderId);
		newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		newTbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
		newTbBizPlaceOrder.setPaymentTime(new Date());
		newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		newTbBizPlaceOrder.setDescrible(memo);
		newTbBizPlaceOrder.setExpression(expression);
		newTbBizPlaceOrder.setHandAdjustAmount(receivedAmount1.subtract(price));


		TbBizPlaceOrderExample updateOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria updateOrderCriteria = updateOrderExample.createCriteria();
		updateOrderCriteria.andPlaceOrderIdEqualTo(reqPlaceOrderId);
		updateOrderCriteria.andOrderStatusEqualTo(PlaceConstants.ORDER_PREPAY_STATUS);
		updateOrderCriteria.andPayStatusEqualTo(PlaceConstants.NOT_PAY_STATUS);
		TbBizPlaceOrder updateOrder = new TbBizPlaceOrder();
		BeanUtils.copyProperties(newTbBizPlaceOrder,updateOrder);
		updateOrder.setId(null);//防止主键冲突
		if (this.tbBizPlaceOrderMapper.updateByExampleSelective(updateOrder,updateOrderExample) != 1){
			throw new Exception("修改订单失败");
		}
		
		//包场开单修该销售计划
		if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
			//修改销售计划
			placeBillingUpdatePlaceUnitSalePlanPlus(adjustTbBizPlaceOrderItems);
		}else if(tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
			logger.debug("小商品和门票,线上支付切换到线下支付，是否减库存待续。。");
		}
		

		//添加会员预订后支付
		//获取会员卡
		TbBizPlaceMemberOpHistoryExample example1 = new TbBizPlaceMemberOpHistoryExample();
		TbBizPlaceMemberOpHistoryExample.Criteria criteria = example1.createCriteria();
		//包场根据父订单号  取会员卡交易历史
		if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
	    	   TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrder.getParentId());
			   criteria.andOrderNoEqualTo(tbBizPlacePrivateOrder.getPlaceOrderId());
		} else {
			criteria.andOrderNoEqualTo(reqPlaceOrderId);
		}
		
		List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example1);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
			logger.debug("非会员订单");
			//修改支付明细
			TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
			tbBizPlacePayItem.setPlaceOrderId(reqPlaceOrderId);
			tbBizPlacePayItem.setAmount(new BigDecimal(receivedAmount));
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
			tbBizPlacePayItem.setPayType(adminPayType);
			tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			if (payItemFlag){
				tbBizPlacePayItem.setId(tbBizPlacePayItemList.get(0).getId());
				tbBizPlacePayItemMapper.updateByPrimaryKeySelective(tbBizPlacePayItem);
			} else {
				tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
			}
		}else{
			String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
			if(org.springframework.util.StringUtils.isEmpty(innerCardNo)){
				throw new Exception("流水会员卡号为空");
			}
			TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
			TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
			tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo)
					.andIsDeleteEqualTo(PlaceConstants.NO).andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
			List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
			if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceMemberCardList)){
				throw new Exception("无效会员卡");
			}
			TbBizPlaceMemberCard tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
			//修改支付明细
			TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
			if (null != tbBizPlaceMemberCard && tbBizPlaceMemberCard.getIsOldMember() == Constants.BYTE_ONE){
				tbBizPlacePayItem.setPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
				tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS)).getUnifiedId());
			} else {
				tbBizPlacePayItem.setPayType(adminPayType);
				tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			}

			tbBizPlacePayItem.setPlaceOrderId(reqPlaceOrderId);
			tbBizPlacePayItem.setAmount(new BigDecimal(receivedAmount));
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);

			if (payItemFlag){
				//// TODO: 2017/5/9 只适应只有一条支付记录的情况
				tbBizPlacePayItem.setId(tbBizPlacePayItemList.get(0).getId());
				tbBizPlacePayItemMapper.updateByPrimaryKeySelective(tbBizPlacePayItem);
			} else {
				tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
			}


			BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
			BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
			BigDecimal zeroAmount = new BigDecimal(0);
			if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE){//储值卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount1));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount1.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount1.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("余额不足");
						}
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT){//折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount1));
					}
					else{
						throw new Exception("余额不足");
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT){//储值折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receivedAmount1));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount1.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount1.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("余额不足");
						}
					}
				}
			}
			tbBizPlaceMemberCard.setUpdateTime(new Date());
			if (tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard) != 1){
				throw new Exception("更新会员卡失败");
			}
			
			TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
			tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
			tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
			tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
			tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
			tbBizPlaceMemberOpHistory.setAmount(receivedAmount1);
			tbBizPlaceMemberOpHistory.setCreateTime(new Date());
			tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
			tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
			tbBizPlaceMemberOpHistory.setOrderNo(reqPlaceOrderId);
			tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName()+"支付");
			tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
			tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
			tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
			tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
			tbBizPlaceMemberOpHistory.setMemo(memo);
			tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
			tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
			tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
			tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
			tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
			tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
			tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
			tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
			tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());
			tbBizPlaceMemberOpHistory.setPayType(adminPayType);
			tbBizPlaceMemberOpHistory.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			//开单做更新处理
			if (!tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
				if (tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKeySelective(tbBizPlaceMemberOpHistory) != 1){
					throw new Exception("修改会员操作明细失败");
				}
			} else {
				//包场子订单按照子订单写入操作明细
				 //退款生成订单号
				if (tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory) != 1){
					throw new Exception("插入会员操作明细失败");
				}
				//父订单状态同步
				checkBlockOrder(tbBizPlaceOrder, newTbBizPlaceOrder.getOrderStatus(), receivedAmount1);
			}
			

			TbBizPlace place=placeBaseService.getPlaceById(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
			List<String> mobileList=new ArrayList<>();
			List<String> paramList=new ArrayList<>();
			//成功消费发送短信提醒
			String [] args=new String[7];
			args[0] = place != null ? place.getName() : "";
			args[1] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getCardName() : "";
			args[2] = DateUtils.getCurrentTime();
			args[3] ="场地预定";
			args[4] = receivedAmount != null ? receivedAmount.toString()+"元":"";
			args[5]=tbBizPlaceMemberCard!=null?tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).toString()+"元":"";
			// 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
			TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
			if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
				args[6]=placeAttach.getBookingConsultPhone();
			} else {
				// 获取系统配置的百灵鸟客服热线
				TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
				args[6]=parameterVo!=null?parameterVo.getParameterValue():"";
			}
			mobileList.add(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
			paramList.addAll(Arrays.asList(args));
			try{
				//placeTicketService.asyncSendSms(tbBizPlaceMemberOpHistoryList.get(0).getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE,args,true);
				placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
			}catch(Exception e){
				logger.info("短信发送失败-------->"+e.getMessage());
			}
		}

		//插入支付流水
		ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(newTbBizPlaceOrder,new BigDecimal(receivedAmount),(byte)0,(byte)0);
		placeOrderUtilService.insertOrderHistory(reqOrderHistory);


		PlacePrintVo placePrintVo = new PlacePrintVo();
		placePrintVo.setPlaceOrderId(reqPlaceOrderId);
		placePrintVo.setBusinessType(tbBizPlaceOrders.get(0).getUseType());
		if (isMember){
			placePrintVo.setIsMember(PlaceConstants.YES);
		} else {
			placePrintVo.setIsMember(PlaceConstants.NO);
		}
		return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
	}
	
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public APIResponse saveBlockPay(String reqPlaceOrderId,Integer adminPayType, String receivedAmount,String memo,String expression) throws Exception {
		BigDecimal receivedAmount1 = new BigDecimal(receivedAmount);
		//查询订单
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);

		//是否会员
		boolean isMember = false;

		if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrders)){
			throw new Exception("没有对应的订单");
		}
		if(tbBizPlaceOrders.size() > 1){
			throw new Exception("订单异常，有重复订单");
		}
		TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrders.get(0);
		if (tbBizPlaceOrder.getOrderStatus() > 1){
			return APIResponse.returnFail("订单状态已更新,无法支付！");
		}
		//支付明细
		TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
		tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
		boolean payItemFlag = false;
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlacePayItemList)){
			payItemFlag = true;
		}

		//订单明细
		//根据placeOrderId拿到placeOrderItem
		TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
		itemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
			throw new Exception("订单明细为null");
		}
		BigDecimal price = new BigDecimal(0);
		List<String> saleIds = new ArrayList<>();
		//拿到销售计划场地Id
		for(TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			saleIds.add(tbBizPlaceOrderItem.getSaleId());
			price = price.add(tbBizPlaceOrderItem.getSalePrice());
		}

		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(receivedAmount1,tbBizPlaceOrderItems,price);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
			tbBizPlaceOrderItemMapper.updateByPrimaryKeySelective(item);
		}

		//修改订单
		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
		org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrder,newTbBizPlaceOrder);
		//修改取消订单状态
		newTbBizPlaceOrder.setId(tbBizPlaceOrder.getId());
		newTbBizPlaceOrder.setPlaceOrderId(reqPlaceOrderId);
		newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		newTbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
		newTbBizPlaceOrder.setPaymentTime(new Date());
		newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		newTbBizPlaceOrder.setDescrible(memo);
		newTbBizPlaceOrder.setExpression(expression);
		newTbBizPlaceOrder.setHandAdjustAmount(receivedAmount1.subtract(price));

		TbBizPlaceOrderExample updateOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria updateOrderCriteria = updateOrderExample.createCriteria();
		updateOrderCriteria.andPlaceOrderIdEqualTo(reqPlaceOrderId);
		updateOrderCriteria.andOrderStatusEqualTo(PlaceConstants.ORDER_PREPAY_STATUS);
		updateOrderCriteria.andPayStatusEqualTo(PlaceConstants.NOT_PAY_STATUS);
		TbBizPlaceOrder updateOrder = new TbBizPlaceOrder();
		BeanUtils.copyProperties(newTbBizPlaceOrder,updateOrder);
		updateOrder.setId(null);//防止主键冲突
		if (this.tbBizPlaceOrderMapper.updateByExampleSelective(updateOrder,updateOrderExample) != 1){
			throw new Exception("修改订单失败");
		}
		
		//修改销售计划
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(saleIds);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)){
			throw new Exception("销售计划为null");
		}

		List<UnitSalePlan> list = new ArrayList<>();
		for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
			UnitSalePlan up = new UnitSalePlan();
			up.setSaleId(tsp.getSaleId());
			list.add(up);
		}
		ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
		reqPlaceOrderListVo.setUnitSalePlanIdList(list);
		reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_ORDER_STATUS);//支付完销售计划状态为已预订——>H5为已售
		if (iBaseService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo) < 1){
			throw new Exception("修改销售计划失败");
		}

		//添加会员预订后支付
		//获取会员卡
		TbBizPlaceMemberOpHistoryExample example1 = new TbBizPlaceMemberOpHistoryExample();
		TbBizPlaceMemberOpHistoryExample.Criteria criteria = example1.createCriteria();
		//包场根据父订单号  取会员卡交易历史
		if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
	    	   TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrder.getParentId());
			   criteria.andOrderNoEqualTo(tbBizPlacePrivateOrder.getPlaceOrderId());
		} else {
			   criteria.andOrderNoEqualTo(reqPlaceOrderId);
		}
		
		Integer serviceSwitch = 0;//拆分开关 1.开,0.关  和APP共用一个
	    TbCommonParameter parameter1 = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
        if (parameter1 != null && parameter1.getParameterValue() != null) {
        	serviceSwitch = Integer.valueOf(parameter1.getParameterValue());
        }

		
		List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example1);

		TbBizPlacePayItemExample updatePayItemExample = new TbBizPlacePayItemExample();
		TbBizPlacePayItemExample.Criteria updatePayItemCriteria = updatePayItemExample.createCriteria();
		updatePayItemCriteria.andPlaceOrderIdEqualTo(reqPlaceOrderId);

		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
			logger.info("非会员订单");
			if (serviceSwitch == 0) {
				TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
				tbBizPlacePayItem.setPlaceOrderId(reqPlaceOrderId);
				tbBizPlacePayItem.setAmount(new BigDecimal(receivedAmount));
				tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
				tbBizPlacePayItem.setPayType(adminPayType);
				tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());

				int flag = 0;
				if (payItemFlag){
					flag = tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,updatePayItemExample);
				} else {
					flag = tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
				}
				if (flag == 0 ){
					throw new Exception("修改支付明细失败");
				}
			} else {
				//修改支付明细--现在改为按  订单明细-->支付明细
				List<TbBizPlacePayItem> placePayItemList = iBaseService.convertOrderPayItem(adjustTbBizPlaceOrderItems, adminPayType, null);
				if (payItemFlag){
					TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
					tbBizPlacePayItem.setPayType(adminPayType);
					tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
					tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,updatePayItemExample);
				} else {
					for (TbBizPlacePayItem tbBizPlacePayItem : placePayItemList) {
						tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
					}
				}
				//写订单折扣明细
				List<TbBizPlaceOrderDiscountItem> placeOrderDiscountItemList =  iBaseService.convertOrderDiscountItem(adjustTbBizPlaceOrderItems, null);
				if (!CollectionUtils.isEmpty(placeOrderDiscountItemList)) {
					for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : placeOrderDiscountItemList) {
						tbBizPlaceOrderDiscountItemMapper.insertSelective(tbBizPlaceOrderDiscountItem);
					}
				}
				//明细转流水
				List<ReqOrderHistory> reqOrderHistoryList = placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(newTbBizPlaceOrder,adjustTbBizPlaceOrderItems,(byte)0,(byte)0,null);
				try {
					placeOrderUtilService.shoppingCartOrderInsertOrderHistory(reqOrderHistoryList);
				} catch (Exception e) {
					e.printStackTrace();
					throw new Exception("生成支付流水异常");
				}
			}
		}else{
			String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
			if(org.springframework.util.StringUtils.isEmpty(innerCardNo)){
				throw new Exception("流水会员卡号为空");
			}
			TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
			TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
			tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo)
					.andIsDeleteEqualTo(PlaceConstants.NO).andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
			List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
			if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceMemberCardList)){
				throw new Exception("无效会员卡");
			}
			TbBizPlaceMemberCard tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
			if (serviceSwitch ==0) {
				//修改支付明细
				TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
				if (null != tbBizPlaceMemberCard && tbBizPlaceMemberCard.getIsOldMember() == Constants.BYTE_ONE){
					tbBizPlacePayItem.setPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
					tbBizPlacePayItem.setAdminPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
				} else {
					tbBizPlacePayItem.setPayType(adminPayType);
					tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
				}

				tbBizPlacePayItem.setPlaceOrderId(reqPlaceOrderId);
				tbBizPlacePayItem.setAmount(new BigDecimal(receivedAmount));
				tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);

				int flag = 0;
				if (payItemFlag){
					flag = tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,updatePayItemExample);
				} else {
					flag = tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
				}
				if (flag == 0 ){
					throw new Exception("修改支付明细失败");
				}
			} else {
				//修改支付明细--现在改为按  订单明细-->支付明细
				List<TbBizPlacePayItem> placePayItemList = iBaseService.convertOrderPayItem(adjustTbBizPlaceOrderItems, adminPayType, tbBizPlaceMemberCard);
				if (payItemFlag){
					TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
					tbBizPlacePayItem.setPayType(adminPayType);
					tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
					tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,updatePayItemExample);
				} else {
					for (TbBizPlacePayItem tbBizPlacePayItem : placePayItemList) {
						tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
					}
				}
				//写订单折扣明细
				List<TbBizPlaceOrderDiscountItem> placeOrderDiscountItemList =  iBaseService.convertOrderDiscountItem(adjustTbBizPlaceOrderItems, tbBizPlaceMemberCard);
				if (!CollectionUtils.isEmpty(placeOrderDiscountItemList)) {
					for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : placeOrderDiscountItemList) {
						tbBizPlaceOrderDiscountItemMapper.insertSelective(tbBizPlaceOrderDiscountItem);
					}
				}
				//明细转流水
				List<ReqOrderHistory> reqOrderHistoryList = placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(newTbBizPlaceOrder,adjustTbBizPlaceOrderItems,(byte)0,(byte)0,tbBizPlaceMemberCard);
				try {
					placeOrderUtilService.shoppingCartOrderInsertOrderHistory(reqOrderHistoryList);
				} catch (Exception e) {
					e.printStackTrace();
					throw new Exception("生成支付流水异常");
				}
			}
			
			BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
			BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
			BigDecimal zeroAmount = new BigDecimal(0);
			if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE){//储值卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount1));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount1.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount1.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("余额不足");
						}
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT){//折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount1));
					}
					else{
						throw new Exception("余额不足");
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT){//储值折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receivedAmount1));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount1.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount1.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("余额不足");
						}
					}
				}
			}
			tbBizPlaceMemberCard.setUpdateTime(new Date());
			if (tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard) != 1){
				throw new Exception("更新会员卡失败");
			}
			
			TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
			tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
			tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
			tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
			tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
			tbBizPlaceMemberOpHistory.setAmount(receivedAmount1);
			tbBizPlaceMemberOpHistory.setCreateTime(new Date());
			tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
			tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
			tbBizPlaceMemberOpHistory.setOrderNo(reqPlaceOrderId);
			tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName()+"支付");
			tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
			tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
			tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
			tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
			tbBizPlaceMemberOpHistory.setMemo(memo);
			tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
			tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
			tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
			tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
			tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
			tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
			tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
			tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
			tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());
			tbBizPlaceMemberOpHistory.setPayType(adminPayType);
			tbBizPlaceMemberOpHistory.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			//开单做更新处理
			if (!tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
				if (tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKeySelective(tbBizPlaceMemberOpHistory) != 1){
					throw new Exception("修改会员操作明细失败");
				}
			} else {
				//包场子订单按照子订单写入操作明细
				 //退款生成订单号
				if (tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory) != 1){
					throw new Exception("插入会员操作明细失败");
				}
				//父订单状态同步
				checkBlockOrder(tbBizPlaceOrder, newTbBizPlaceOrder.getOrderStatus(), receivedAmount1);
			}

			TbBizPlace place=placeBaseService.getPlaceById(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
			List<String> mobileList=new ArrayList<>();
			List<String> paramList=new ArrayList<>();
			//成功消费发送短信提醒
			String [] args=new String[7];
			args[0] = place != null ? place.getName() : "";
			args[1] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getCardName() : "";
			args[2] = DateUtils.getCurrentTime();
			args[3] ="场地预定";
			args[4] = receivedAmount != null ? receivedAmount.toString()+"元":"";
			args[5]=tbBizPlaceMemberCard!=null?tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).toString()+"元":"";
			// 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
			TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
			if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
				args[6]=placeAttach.getBookingConsultPhone();
			} else {
				// 获取系统配置的百灵鸟客服热线
				TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
				args[6]=parameterVo!=null?parameterVo.getParameterValue():"";
			}
			mobileList.add(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
			paramList.addAll(Arrays.asList(args));
			try{
				//placeTicketService.asyncSendSms(tbBizPlaceMemberOpHistoryList.get(0).getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE,args,true);
				placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
			}catch(Exception e){
				logger.info("短信发送失败-------->"+e.getMessage());
			}
			isMember = true;

		}
		if (serviceSwitch == 0) {
//			//插入支付流水
			ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(newTbBizPlaceOrder,new BigDecimal(receivedAmount),(byte)0,(byte)0);
			placeOrderUtilService.insertOrderHistory(reqOrderHistory);
		}
		PlacePrintVo placePrintVo = new PlacePrintVo();
		placePrintVo.setPlaceOrderId(reqPlaceOrderId);
		placePrintVo.setBusinessType(tbBizPlaceOrders.get(0).getUseType());
		if (isMember){
			placePrintVo.setIsMember(PlaceConstants.YES);
		} else {
			placePrintVo.setIsMember(PlaceConstants.NO);
		}
		return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
	}


	/**
	 * 查询是否可以锁定库存，如果可以直接锁定库存（改变销售计划的状态，设置为锁定状态）,返回下单信息(这里需要支持组合场地的锁定)
	 * * @param reqPlaceOrderListVo
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public List<TbBizPlaceUnitSalePlan>  lockTbBizPlaceUnitSalePlanEx(ReqPlaceOrderListVo reqPlaceOrderListVo, Byte status){
		reqPlaceOrderListVo.setIsLockQuery(true);

		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqPlaceOrderListVo);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanListResult = new ArrayList<>();
		if(!com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)) {
			return null;
		}

		// 注意这里要考虑到子场被多次包含的问题
		APIResponse apiResponse = null;
		apiResponse = salePlansVerification(tbBizPlaceUnitSalePlanList);
		if (apiResponse != null) {
			return null;
		}

		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
			if (UNIT_TYPE_BASE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
				if(!tbBizPlaceUnitSalePlan.getStatus().equals(PlaceConstants.PLACE_PREORDER_STATUS)) {
					tbBizPlaceUnitSalePlanListResult.add(tbBizPlaceUnitSalePlan);
					return tbBizPlaceUnitSalePlanListResult;
				}
			} else if (UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
				// 先取出对应的子销售计划
				Integer placeId = reqPlaceOrderListVo.getPlaceId();
				List<TbBizPlaceUnitSalePlan> subSalePlans = new ArrayList<>();
				boolean valid = getCombineSubSalePlanList(placeId, tbBizPlaceUnitSalePlan, subSalePlans);

				Boolean canLock = true;
				Byte combineStatus = PlaceConstants.PLACE_PREORDER_STATUS;

				if (!valid || subSalePlans.size() <= 0) {
					canLock = false;
					combineStatus = PlaceConstants.PLACE_LOCk_STATUS;
				} else {
					for (TbBizPlaceUnitSalePlan subSalePlan : subSalePlans) {
						if(!subSalePlan.getStatus().equals(PlaceConstants.PLACE_PREORDER_STATUS)){
							canLock = false;
							combineStatus = subSalePlan.getStatus();
							break;
						}
					}
				}

				if (!canLock) {
					tbBizPlaceUnitSalePlan.setStatus(combineStatus);
					tbBizPlaceUnitSalePlanListResult.add(tbBizPlaceUnitSalePlan);
					return tbBizPlaceUnitSalePlanListResult;
				}
			}
		}

		//更新数据库为锁定状态
		reqPlaceOrderListVo.setStatus(status);
		reqPlaceOrderListVo.setLockTime(DateUtils.transferLongToDate(System.currentTimeMillis()));
		//int result = placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
		updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);

		return tbBizPlaceUnitSalePlanList;
	}

	/*
    更新订单中销售计划[可能是组合场地的销售计划]的状态
     */
	@Override
	public int updateSalePlanByPrimaryKeyList(ReqPlaceOrderListVo reqPlaceOrderListVo) {
		int subSucc = 0;
		int idSize = 0;
		int saleIdSize = 0;

		List<UnitSalePlan> unitSalePlanList = reqPlaceOrderListVo.getUnitSalePlanIdList();
		if (unitSalePlanList != null) {
			saleIdSize =  unitSalePlanList.size();
		}
		List<Integer> salePlanIdList = reqPlaceOrderListVo.getSalePlanPrimaryKeyList();
		if (salePlanIdList != null) {
			idSize = salePlanIdList.size();
		}

		if (saleIdSize > 0 && idSize > 0 && saleIdSize != idSize) {
			return -1;
		}

		// 先查询每个销售计划的类型 (使用已有接口)
		ReqPlaceOrderListVo reqTemp = new ReqPlaceOrderListVo();
		reqTemp.setUnitSalePlanIdList(reqPlaceOrderListVo.getUnitSalePlanIdList());
		reqTemp.setSalePlanPrimaryKeyList(reqPlaceOrderListVo.getSalePlanPrimaryKeyList());
		if (CollectionUtils.isEmpty(reqPlaceOrderListVo.getUnitSalePlanIdList())&& CollectionUtils.isEmpty(reqPlaceOrderListVo.getSalePlanPrimaryKeyList())) {
			return -1;
		}
		List<TbBizPlaceUnitSalePlan> salePlans = placeUnitSalePlanMapper.selectSalePlanForUpdate(reqTemp);
		if (salePlans != null && salePlans.size() > 0) {
			for (TbBizPlaceUnitSalePlan salePlan : salePlans) {
				// 如果是组合场地的订单,要同时更新子场地销售计划
				if (PlaceConstants.UNIT_TYPE_COMBINE.equals(salePlan.getUnitType())) {
					String subSaleplans = salePlan.getSubSaleplans();
					if (subSaleplans == null || subSaleplans.isEmpty()) {
						continue;
					}

					List<String> subSalePlanIds = Arrays.asList(subSaleplans.split("[|]"));
					List<UnitSalePlan> subSalePlanList = new ArrayList<>();

					if (subSalePlanIds != null && subSalePlanIds.size() > 0) {
						for (String salePlanId : subSalePlanIds) {
							UnitSalePlan subUSP = new UnitSalePlan();
							subUSP.setSaleId(salePlanId);
							subSalePlanList.add(subUSP);
						}
					}

					if (subSalePlanList.size() > 0) {
						ReqPlaceOrderListVo subReq = new ReqPlaceOrderListVo();
						BeanCopierUtils.copyProperties(reqPlaceOrderListVo, subReq);

						subReq.setUnitSalePlanIdList(subSalePlanList);
						subReq.setSalePlanPrimaryKeyList(null);
						int ret = placeUnitSalePlanMapper.updateByPrimaryKeyList(subReq);
						if (ret >= subSalePlanList.size()) {
							subSucc++;
						} else {
							if (reqPlaceOrderListVo.getPreStatus() != null) {
								throw new BizException("场地已被预定");
							}
						}
					}
				} else {
					subSucc++;
				}
			}
		}

		if (subSucc < idSize || subSucc < saleIdSize) {
			return -1;
		}

		int result =  placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
		if (result < idSize || result < saleIdSize) {
			if (reqPlaceOrderListVo.getPreStatus() != null) {
				throw new BizException("场地已被预定");
			}
		}
		return result;
	}

	/**
	 * 查询是否可以锁定库存，如果可以直接锁定库存（改变销售计划的状态，设置为锁定状态）,返回下单信息(这里需要支持组合场地的锁定)  增强 by yxj
	 * * @param reqPlaceOrderListVo
	 * @return
	 */
	@Override
	public List<TbBizPlaceUnitSalePlan>  lockTbBizPlaceUnitSalePlanExPlus(ReqPlaceOrderListVo reqPlaceOrderListVo) throws Exception{
		reqPlaceOrderListVo.setIsLockQuery(true);

		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqPlaceOrderListVo);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanListResult = new ArrayList<>();
		if(!com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)) {
			return null;
		}

		// 注意这里要考虑到子场被多次包含的问题
		APIResponse apiResponse = null;
		apiResponse = salePlansVerification(tbBizPlaceUnitSalePlanList);
		if (apiResponse != null) {
			throw new BizException("场地间存在组合-子场重叠");
		}

		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
			if (UNIT_TYPE_BASE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
				if(!tbBizPlaceUnitSalePlan.getStatus().equals(PlaceConstants.PLACE_PREORDER_STATUS)
						&& !tbBizPlaceUnitSalePlan.getStatus().equals(PlaceConstants.PLACE_BACKGROUND_STATUS)) {
					tbBizPlaceUnitSalePlanListResult.add(tbBizPlaceUnitSalePlan);
					return tbBizPlaceUnitSalePlanListResult;
				}
			} else if (UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
				// 先取出对应的子销售计划
				Integer placeId = reqPlaceOrderListVo.getPlaceId();
				List<TbBizPlaceUnitSalePlan> subSalePlans = new ArrayList<>();
				boolean valid = getCombineSubSalePlanList(placeId, tbBizPlaceUnitSalePlan, subSalePlans);

				Boolean canLock = true;
				Byte combineStatus = PlaceConstants.PLACE_PREORDER_STATUS;

				if (!valid || subSalePlans.size() <= 0) {
					canLock = false;
					combineStatus = PlaceConstants.PLACE_LOCk_STATUS;
				} else {
					for (TbBizPlaceUnitSalePlan subSalePlan : subSalePlans) {
						if(!subSalePlan.getStatus().equals(PlaceConstants.PLACE_PREORDER_STATUS)
								&& !subSalePlan.getStatus().equals(PlaceConstants.PLACE_BACKGROUND_STATUS)){
							canLock = false;
							combineStatus = subSalePlan.getStatus();
							break;
						}
					}
				}

				if (!canLock) {
					tbBizPlaceUnitSalePlan.setStatus(combineStatus);
					tbBizPlaceUnitSalePlanListResult.add(tbBizPlaceUnitSalePlan);
					return tbBizPlaceUnitSalePlanListResult;
				}
			}
		}

		//更新数据库为锁定状态
		reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_LOCk_STATUS);
		reqPlaceOrderListVo.setLockTime(DateUtils.transferLongToDate(System.currentTimeMillis()));

		int flag = updateSalePlanLockStatus(reqPlaceOrderListVo);
		if (flag < 1){
			throw new BizException("场地已被锁定");
		}

		return tbBizPlaceUnitSalePlanList;
	}

	/*
    更新销售计划[可能是组合场地的销售计划]的状态 为 2  【2：锁定】
     */
	@Override
	public int updateSalePlanLockStatus(ReqPlaceOrderListVo reqPlaceOrderListVo) throws Exception{
		int subSucc = 0;
		int idSize = 0;
		int saleIdSize = 0;

		List<UnitSalePlan> unitSalePlanList = reqPlaceOrderListVo.getUnitSalePlanIdList();
		if (unitSalePlanList != null) {
			saleIdSize =  unitSalePlanList.size();
		}
		List<Integer> salePlanIdList = reqPlaceOrderListVo.getSalePlanPrimaryKeyList();
		if (salePlanIdList != null) {
			idSize = salePlanIdList.size();
		}

		if (saleIdSize > 0 && idSize > 0 && saleIdSize != idSize) {
			return -1;
		}

		// 先查询每个销售计划的类型 (使用已有接口)
		ReqPlaceOrderListVo reqTemp = new ReqPlaceOrderListVo();
		reqTemp.setUnitSalePlanIdList(reqPlaceOrderListVo.getUnitSalePlanIdList());
		reqTemp.setSalePlanPrimaryKeyList(reqPlaceOrderListVo.getSalePlanPrimaryKeyList());
		if (CollectionUtils.isEmpty(reqPlaceOrderListVo.getUnitSalePlanIdList())&& CollectionUtils.isEmpty(reqPlaceOrderListVo.getSalePlanPrimaryKeyList())) {
			return -1;
		}
		List<TbBizPlaceUnitSalePlan> salePlans = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqTemp);
		if (salePlans != null && salePlans.size() > 0) {
			for (TbBizPlaceUnitSalePlan salePlan : salePlans) {

				// 如果是组合场地的订单,要同时更新子场地销售计划
				if (PlaceConstants.UNIT_TYPE_COMBINE.equals(salePlan.getUnitType())) {
					String subSaleplans = salePlan.getSubSaleplans();
					if (subSaleplans == null || subSaleplans.isEmpty()) {
						continue;
					}

					List<String> subSalePlanIds = Arrays.asList(subSaleplans.split("[|]"));
					List<UnitSalePlan> subSalePlanList = new ArrayList<>();

					if (subSalePlanIds != null && subSalePlanIds.size() > 0) {
						for (String salePlanId : subSalePlanIds) {
							UnitSalePlan subUSP = new UnitSalePlan();
							subUSP.setSaleId(salePlanId);
							subSalePlanList.add(subUSP);
						}
					}

					if (subSalePlanList.size() > 0) {
						ReqPlaceOrderListVo subReq = new ReqPlaceOrderListVo();
						BeanCopierUtils.copyProperties(reqPlaceOrderListVo, subReq);

						subReq.setUnitSalePlanIdList(subSalePlanList);
						subReq.setSalePlanPrimaryKeyList(null);
						int ret = placeUnitSalePlanMapper.updateSalePlanLockStatus(subReq);
						if (ret < subSalePlanList.size()){
							throw new BizException("存在其他场地已被锁定 错误码:-1");
						}
						if (ret >= subSalePlanList.size()) {
							subSucc++;
						}
					}
				} else {
					subSucc++;
				}
			}
		}

		if (subSucc < idSize || subSucc < saleIdSize) {
			return -1;
		}
		int flag = placeUnitSalePlanMapper.updateSalePlanLockStatus(reqPlaceOrderListVo);
		if (flag < 1){
			throw new BizException("场地已被锁定 错误码:-2");
		}
		return flag;
	}

	/*
    更新销售计划[可能是组合场地的销售计划]的状态 3 【3：已售出】
     */
	@Override
	public int updateSalePlanOrderStatus(ReqPlaceOrderListVo reqPlaceOrderListVo) throws Exception{
		int subSucc = 0;
		int idSize = 0;
		int saleIdSize = 0;

		List<UnitSalePlan> unitSalePlanList = reqPlaceOrderListVo.getUnitSalePlanIdList();
		if (unitSalePlanList != null) {
			saleIdSize =  unitSalePlanList.size();
		}
		List<Integer> salePlanIdList = reqPlaceOrderListVo.getSalePlanPrimaryKeyList();
		if (salePlanIdList != null) {
			idSize = salePlanIdList.size();
		}

		if (saleIdSize > 0 && idSize > 0 && saleIdSize != idSize) {
			return -1;
		}

		// 先查询每个销售计划的类型 (使用已有接口)
		ReqPlaceOrderListVo reqTemp = new ReqPlaceOrderListVo();
		reqTemp.setUnitSalePlanIdList(reqPlaceOrderListVo.getUnitSalePlanIdList());
		reqTemp.setSalePlanPrimaryKeyList(reqPlaceOrderListVo.getSalePlanPrimaryKeyList());
		if (CollectionUtils.isEmpty(reqPlaceOrderListVo.getUnitSalePlanIdList())&& CollectionUtils.isEmpty(reqPlaceOrderListVo.getSalePlanPrimaryKeyList())) {
			return -1;
		}
		List<TbBizPlaceUnitSalePlan> salePlans = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqTemp);
		if (salePlans != null && salePlans.size() > 0) {
			for (TbBizPlaceUnitSalePlan salePlan : salePlans) {
				// 如果是组合场地的订单,要同时更新子场地销售计划
				if (PlaceConstants.UNIT_TYPE_COMBINE.equals(salePlan.getUnitType())) {
					String subSaleplans = salePlan.getSubSaleplans();
					if (subSaleplans == null || subSaleplans.isEmpty()) {
						continue;
					}

					List<String> subSalePlanIds = Arrays.asList(subSaleplans.split("[|]"));
					List<UnitSalePlan> subSalePlanList = new ArrayList<>();

					if (subSalePlanIds != null && subSalePlanIds.size() > 0) {
						for (String salePlanId : subSalePlanIds) {
							UnitSalePlan subUSP = new UnitSalePlan();
							subUSP.setSaleId(salePlanId);
							subSalePlanList.add(subUSP);
						}
					}

					if (subSalePlanList.size() > 0) {
						ReqPlaceOrderListVo subReq = new ReqPlaceOrderListVo();
						BeanCopierUtils.copyProperties(reqPlaceOrderListVo, subReq);

						subReq.setUnitSalePlanIdList(subSalePlanList);
						subReq.setSalePlanPrimaryKeyList(null);
						int ret = placeUnitSalePlanMapper.updateSalePlanOrderStatus(subReq);
						if (ret < subSalePlanList.size()){
							throw new BizException("存在其他场地已被预订 错误码:-1");
						}
						if (ret >= subSalePlanList.size()) {
							subSucc++;
						}
					}
				} else {
					subSucc++;
				}
			}
		}

		if (subSucc < idSize || subSucc < saleIdSize) {
			return -1;
		}
		int flag = placeUnitSalePlanMapper.updateSalePlanOrderStatus(reqPlaceOrderListVo);
		if (flag < 1){
			throw new BizException("场地已被预订 错误码:-2");
		}
		return flag;
	}

	/**
	 * 支付后修改销售计划状态
	 * @param tbBizPlaceOrderItems
	 */
	public void placeBillingUpdatePlaceUnitSalePlanPlus(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems) throws Exception{
		List<String> ids = new ArrayList<String>();
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
			ids.add(tbBizPlaceOrderItem.getSaleId());
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(ids);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = tbBizPlaceUnitSalePlanMapper
				.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)){
			return;
		}
		List<UnitSalePlan> list = new ArrayList<UnitSalePlan>();
		for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
			UnitSalePlan up = new UnitSalePlan();
			up.setSaleId(tsp.getSaleId());
			list.add(up);
		}
		ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
		reqPlaceOrderListVo.setUnitSalePlanIdList(list);
		reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_ORDER_STATUS);//预订——>销售计划状态改成已预订
		try {
			int flag = this.updateSalePlanOrderStatus(reqPlaceOrderListVo);
			if (flag < 1){
				throw new BizException("场地已被预订 错误码:-3");
			}
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 检验销售计划有没有重叠
	 * @param tbBizPlaceUnitSalePlanList
	 * @return
	 */
	@Override
	public APIResponse salePlansVerification(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList) {
		Set<String> uniqSaleIds = new HashSet<>();

		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
			List<String> saleIds = new ArrayList<>();

			if (tbBizPlaceUnitSalePlan == null) {
				continue;
			}

			String saleId = tbBizPlaceUnitSalePlan.getSaleId();
			if (saleId != null) {
				saleIds.add(saleId);
			}

			if (UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
				String subSaleplans = tbBizPlaceUnitSalePlan.getSubSaleplans();
				List<String> subSaleplanIds = new ArrayList<>();
				if (subSaleplans != null) {
					subSaleplanIds = Arrays.asList(subSaleplans.split("[|]"));
				}

				if (subSaleplanIds != null && subSaleplanIds.size() > 0) {
					saleIds.addAll(subSaleplanIds);
				}
			}

			for (String curSaleId : saleIds) {
				if (uniqSaleIds.contains(curSaleId)) {
					return APIResponse.returnFail("销售计划" + saleId + "有重叠！" );
				} else {
					uniqSaleIds.add(curSaleId);
				}
			}
		}

		return null;
	}

	public  boolean getCombineSubSalePlanList(Integer placeId, TbBizPlaceUnitSalePlan combineSalePlan, List<TbBizPlaceUnitSalePlan> subSalePlanList)  {
		boolean valid = false;

		Byte unitType = combineSalePlan.getUnitType();
		if (unitType != null && UNIT_TYPE_BASE.equals(unitType)) {
			valid = false;
		} else {
			String subSaleplans = combineSalePlan.getSubSaleplans();
			if (subSaleplans == null || subSaleplans.isEmpty()) {
				TbBizPlaceUnitSalePlan tbCSP = null;
				if (combineSalePlan.getId() != null) {
					tbCSP = tbBizPlaceUnitSalePlanMapper.selectByPrimaryKey(combineSalePlan.getId());
				} else if (combineSalePlan.getSaleId() != null) {
					TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
					TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
					criteria.andPlaceIdEqualTo(placeId);
					criteria.andSaleIdEqualTo(combineSalePlan.getSaleId());

					List<TbBizPlaceUnitSalePlan> pusps = tbBizPlaceUnitSalePlanMapper.selectByExample(example);
					if (pusps != null && pusps.size() > 0) {
						tbCSP = pusps.get(0);
					}
				}

				if (tbCSP != null) {
					subSaleplans = tbCSP.getSubSaleplans();
				}
			}

			List<String> subSaleplanIds = new ArrayList<>();
			if (subSaleplans != null) {
				subSaleplanIds = Arrays.asList(subSaleplans.split("[|]"));
			}

			// 从数据库中读取
			if (subSaleplanIds.size() > 0) {
				TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
				TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
				criteria.andPlaceIdEqualTo(placeId);
				criteria.andSaleIdIn(subSaleplanIds);
				List<TbBizPlaceUnitSalePlan> temp = tbBizPlaceUnitSalePlanMapper.selectByExample(example);
				if (temp != null) {
					subSalePlanList.addAll(temp);
				}

				if (subSaleplanIds != null && subSalePlanList.size() == subSaleplanIds.size()) {
					valid = true;
				}
			}
		}

		return valid;
	}

	/**
	 * 场地销售计划转换订单明细
	 * @param tbBizPlaceUnitSalePlanList
	 * @param placeOrderId
	 * @return
	 */
	List<TbBizPlaceOrderItem> tbBizPlaceUnitSalePlan2OrderItem(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList,
															   String placeOrderId,
															   Integer status,
															   Integer createUid,
															   Integer updateUid){
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = new ArrayList<TbBizPlaceOrderItem>();
		for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList){
			TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
			tbBizPlaceOrderItem.setPlaceOrderId(placeOrderId);
			tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
			tbBizPlaceOrderItem.setUseType(PlaceConstants.ORDER_USE_BILLING);
			tbBizPlaceOrderItem.setGoodsId(tbBizPlaceUnitSalePlan.getId());
			tbBizPlaceOrderItem.setGoodsName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
			tbBizPlaceOrderItem.setSurplusGoodsCount(1);
			tbBizPlaceOrderItem.setTotalGoodsCount(1);
			tbBizPlaceOrderItem.setTicketCount(1);
			tbBizPlaceOrderItem.setUnitSalePlanId(tbBizPlaceUnitSalePlan.getId());
			tbBizPlaceOrderItem.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
			tbBizPlaceOrderItem.setStartTime(tbBizPlaceUnitSalePlan.getStartTime());
			tbBizPlaceOrderItem.setEndTime(tbBizPlaceUnitSalePlan.getEndTime());
			tbBizPlaceOrderItem.setVersion(tbBizPlaceUnitSalePlan.getVersion());
			tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getPrice());//散客价
			tbBizPlaceOrderItem.setOriginPrice(tbBizPlaceUnitSalePlan.getPrice());
			tbBizPlaceOrderItem.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
			tbBizPlaceOrderItem.setCreateUid(createUid);
			tbBizPlaceOrderItem.setUpdateUid(updateUid);
			tbBizPlaceOrderItem.setConsumeTime(tbBizPlaceUnitSalePlan.getDate());
			tbBizPlaceOrderItem.setStatus(status);
			tbBizPlaceOrderItem.setCategoryId(tbBizPlaceUnitSalePlan.getCategoryId());
			tbBizPlaceOrderItem.setIsGive(PlaceConstants.NO);
			tbBizPlaceOrderItems.add(tbBizPlaceOrderItem);
		}
		return tbBizPlaceOrderItems;
	}

	/**
	 * 门票销售计划转换订单明细
	 * @param reqTicketSaleList
	 * @param placeOrderId
	 * @param createUid
	 * @param updateUid
     * @return
     */
	List<TbBizPlaceOrderItem> tbTicketSalePlan2OrderItem(List<ReqTicketSale> reqTicketSaleList,
															   String placeOrderId,
														       Integer status,
															   Integer createUid,
															   Integer updateUid){
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = new ArrayList<TbBizPlaceOrderItem>();
		for (ReqTicketSale reqTicketSale : reqTicketSaleList){
			TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
			TbPlaceTicketSalePlan tbPlaceTicketSalePlan = tbPlaceTicketSalePlanMapper
					.selectByPrimaryKey(reqTicketSale.getTicketId());
			tbBizPlaceOrderItem.setPlaceOrderId(placeOrderId);
			tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
			tbBizPlaceOrderItem.setUseType(PlaceConstants.ORDER_USE_TICKET);
			tbBizPlaceOrderItem.setGoodsId(tbPlaceTicketSalePlan.getId());
			tbBizPlaceOrderItem.setGoodsName(tbPlaceTicketSalePlan.getTicketName());
			tbBizPlaceOrderItem.setSurplusGoodsCount(reqTicketSale.getCount());
			tbBizPlaceOrderItem.setTotalGoodsCount(reqTicketSale.getCount());
			tbBizPlaceOrderItem.setUnitSalePlanId(tbPlaceTicketSalePlan.getId());
			tbBizPlaceOrderItem.setSaleId(tbPlaceTicketSalePlan.getSaleNo());
			tbBizPlaceOrderItem.setStartTime(tbPlaceTicketSalePlan.getStartTime());
			tbBizPlaceOrderItem.setEndTime(tbPlaceTicketSalePlan.getEndTime());
			tbBizPlaceOrderItem.setVersion(0);
			tbBizPlaceOrderItem.setSalePrice(tbPlaceTicketSalePlan.getPrice());//散客价
			tbBizPlaceOrderItem.setOriginPrice(tbPlaceTicketSalePlan.getPrice());
			tbBizPlaceOrderItem.setMemberPrice(tbPlaceTicketSalePlan.getMemberPrice());
			tbBizPlaceOrderItem.setCreateUid(createUid);
			tbBizPlaceOrderItem.setUpdateUid(updateUid);
			tbBizPlaceOrderItem.setConsumeTime(new Date());
			tbBizPlaceOrderItem.setStatus(status);
			tbBizPlaceOrderItem.setCategoryId(reqTicketSale.getCategoryId());
			tbBizPlaceOrderItem.setTicketCount(reqTicketSale.getCount());
			tbBizPlaceOrderItem.setIsGive(PlaceConstants.NO);
			tbBizPlaceOrderItems.add(tbBizPlaceOrderItem);
		}
		return tbBizPlaceOrderItems;
	}

	/**
	 * 商品销售转换订单明细
	 * @param placeGoodsVoList
	 * @param placeOrderId
	 * @param createUid
	 * @param updateUid
     * @return
     */
	List<TbBizPlaceOrderItem> tbGoods2OrderItem(List<ReqPlaceGoodsVo> placeGoodsVoList,
														 String placeOrderId,
														 Integer status,
														 Integer createUid,
														 Integer updateUid){
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = new ArrayList<TbBizPlaceOrderItem>();
		for (ReqPlaceGoodsVo reqPlaceGoodsVo : placeGoodsVoList){
			TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
			TbBizPlaceGoods tbBizPlaceGoods = tbBizPlaceGoodsMapper
					.selectByPrimaryKey(reqPlaceGoodsVo.getId());
			tbBizPlaceOrderItem.setPlaceOrderId(placeOrderId);
			tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
			tbBizPlaceOrderItem.setUseType(PlaceConstants.ORDER_USE_GOODS);
			tbBizPlaceOrderItem.setGoodsId(tbBizPlaceGoods.getId());
			tbBizPlaceOrderItem.setGoodsName(tbBizPlaceGoods.getName());
			tbBizPlaceOrderItem.setSurplusGoodsCount(reqPlaceGoodsVo.getGoodsCount());
			tbBizPlaceOrderItem.setTotalGoodsCount(reqPlaceGoodsVo.getGoodsCount());
			tbBizPlaceOrderItem.setUnitSalePlanId(tbBizPlaceGoods.getId());
			tbBizPlaceOrderItem.setSaleId(tbBizPlaceGoods.getGoodsId());
			tbBizPlaceOrderItem.setVersion(0);
			tbBizPlaceOrderItem.setCreateUid(createUid);
			tbBizPlaceOrderItem.setUpdateUid(updateUid);
			tbBizPlaceOrderItem.setConsumeTime(new Date());
			tbBizPlaceOrderItem.setStatus(status);
			tbBizPlaceOrderItem.setCategoryId(0);
			tbBizPlaceOrderItem.setTicketCount(reqPlaceGoodsVo.getGoodsCount());
			tbBizPlaceOrderItem.setCostPrice(tbBizPlaceGoods.getCostPrice());
			tbBizPlaceOrderItem.setIsGive(reqPlaceGoodsVo.getGive().byteValue());
			if (reqPlaceGoodsVo.getGive().byteValue()== PlaceConstants.YES){//赠送
				tbBizPlaceOrderItem.setSalePrice(BigDecimal.ZERO);//0元
				tbBizPlaceOrderItem.setOriginPrice(BigDecimal.ZERO);
				tbBizPlaceOrderItem.setMemberPrice(BigDecimal.ZERO);
			} else {
				tbBizPlaceOrderItem.setSalePrice(tbBizPlaceGoods.getSalePrice());//散客价
				tbBizPlaceOrderItem.setOriginPrice(tbBizPlaceGoods.getSalePrice());
				tbBizPlaceOrderItem.setMemberPrice(tbBizPlaceGoods.getMemberPrice());
			}
			tbBizPlaceOrderItems.add(tbBizPlaceOrderItem);
		}
		return tbBizPlaceOrderItems;
	}

	/**
	 * 校验购物车中的场地信息
	 * @param reqShoppingCart
	 */
	private APIResponse<?> checkGoodCartForBilling(ReqShoppingCart reqShoppingCart,final boolean checkBilling) throws Exception{
		Map reqPlaceOrderListVoTbBizPlaceUnitSalePlansMap = new HashMap();

		if (org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getReqBillingInfo().getPlaceUnitId())){
			return APIResponse.returnFail("场地id不可为空");
		}
		String[] unitids = org.apache.commons.lang3.StringUtils.split(reqShoppingCart.getReqBillingInfo().getPlaceUnitId(), ",");
		List<UnitSalePlan> list = new ArrayList<>();
		ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
		List unitidss = new ArrayList();
		for (String unitid : unitids) {
			UnitSalePlan unit = new UnitSalePlan();
			unit.setSaleId(unitid);
			list.add(unit);
			unitidss.add(unitid);
		}
		reqPlaceOrderListVo.setUnitSalePlanIdList(list);

		if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getPlaceId())) {
			reqPlaceOrderListVo.setPlaceId(reqShoppingCart.getPlaceId());
		}

		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
		criteria.andSaleIdIn(unitidss);
		if (reqPlaceOrderListVo.getPlaceId() != null){
			criteria.andPlaceIdEqualTo(reqPlaceOrderListVo.getPlaceId());
		}
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);

		//判断是否可销售
		if (checkBilling){
			TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = iBaseService.getNotSellPlan(tbBizPlaceUnitSalePlans);
			if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
				return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
			}

			try {
				lockTbBizPlaceUnitSalePlanExPlus(reqPlaceOrderListVo);
			} catch (Exception e){
				throw e;
			}
		}
		//判断组合场合基本场销售计划间有没有重叠
		APIResponse apiResponse = salePlansVerification(tbBizPlaceUnitSalePlans);
		if (apiResponse != null) {
			return APIResponse.returnFail("场地间存在组合-子场重叠");
		}

		reqPlaceOrderListVoTbBizPlaceUnitSalePlansMap.put("tbBizPlaceUnitSalePlans",tbBizPlaceUnitSalePlans);
		reqPlaceOrderListVoTbBizPlaceUnitSalePlansMap.put("reqPlaceOrderListVo",reqPlaceOrderListVo);

		return APIResponse.returnSuccess(reqPlaceOrderListVoTbBizPlaceUnitSalePlansMap);
	}

	/**
	 * 校验购物车中的门票信息
	 * @param reqShoppingCart
	 */
	private APIResponse<?> checkGoodCartForTicket(ReqShoppingCart reqShoppingCart){
		List<ReqTicketSale> reqTicketSaleList = reqShoppingCart.getReqTicketPay().getTicketSaleList();
		if (CollectionUtils.isEmpty(reqTicketSaleList)){
			return APIResponse.returnFail("没有选择门票！");
		}
		if (org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getCreateUid())){
			return APIResponse.returnFail("createUid不能为空！");
		}
		/*if (reqTicketSaleList.size() > 1){
			return APIResponse.returnFail("不支持购买多种门票！");
		}*/
		return APIResponse.returnSuccess();
	}

	/**
	 * 校验购物车中的小商品信息
	 * @param reqPlaceGoodsVoPara
	 */
	public APIResponse<?> checkGoodCartForGoods(ReqPlaceGoodsVo reqPlaceGoodsVoPara){
		if (org.springframework.util.StringUtils.isEmpty(reqPlaceGoodsVoPara)){
			return APIResponse.returnFail("请求参数异常");
		}
		if (CollectionUtils.isEmpty(reqPlaceGoodsVoPara.getGoodsList())){
			return APIResponse.returnFail("请求商品列表为空");
		}
		List<ReqPlaceGoodsVo> placeGoodsVoList = reqPlaceGoodsVoPara.getGoodsList();
		HashMap<Integer,Integer> goodsMap = new HashMap<>();
		for (ReqPlaceGoodsVo reqPlaceGoodsVo : placeGoodsVoList){
			if (org.springframework.util.StringUtils.isEmpty(reqPlaceGoodsVo.getGive())){
				return APIResponse.returnFail("para give must input 0 or 1");
			}
			if (!goodsMap.containsKey(reqPlaceGoodsVo.getId())){
				goodsMap.put(reqPlaceGoodsVo.getId(),reqPlaceGoodsVo.getGoodsCount());
			} else {
				Integer goodsCount = goodsMap.get(reqPlaceGoodsVo.getId());
				goodsCount = goodsCount + reqPlaceGoodsVo.getGoodsCount();
				goodsMap.put(reqPlaceGoodsVo.getId(),goodsCount);
			}
		}
		for (ReqPlaceGoodsVo reqPlaceGoodsVo : placeGoodsVoList){
			TbBizPlaceGoods tbBizPlaceGoods = tbBizPlaceGoodsMapper.selectByPrimaryKey(reqPlaceGoodsVo.getId());
			if (tbBizPlaceGoods.getInventory() < goodsMap.get(reqPlaceGoodsVo.getId())){
				APIResponse errResponse = new APIResponse();
				errResponse.setApiResponseEnum(PlaceErrorCodeEnum.GOODS_INVENTORY_NOT_ENOUGH);
				errResponse.setData(tbBizPlaceGoods);
				return errResponse;
			}
		}
		return APIResponse.returnSuccess();
	}

	/**
	 * 购物车预订再支付
	 * @param reqPlaceOrderId
	 * @param adminPayType
	 * @param receivedAmount
	 * @param memo
	 * @param expression
	 * @param scanCode
     * @return
     * @throws Exception
     */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public APIResponse<?> shoppingCartBookPay(String reqPlaceOrderId, Integer adminPayType, String receivedAmount, String memo, String expression, String scanCode) throws Exception {
		BigDecimal receivedAmount1 = new BigDecimal(receivedAmount);
		//查询订单
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);

		//是否会员
		boolean isMember = false;

		if(CollectionUtils.isEmpty(tbBizPlaceOrders)){
			throw new Exception("没有对应的订单");
		}
		if(tbBizPlaceOrders.size() > 1){
			throw new Exception("订单异常，有重复订单");
		}
		TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrders.get(0);
		if (tbBizPlaceOrder.getOrderStatus() > 1){
			return APIResponse.returnFail("订单状态已更新,无法支付！");
		}

		//支付明细
		TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
		tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlacePayItemList)){
			for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList){
				if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(tbBizPlacePayItem.getPayType().toString())){
					throw new BizException("对公转账不支持再次支付");
				}
			}
			throw new Exception("该订单已有支付信息，不能再支付！");
		}

		//根据placeOrderId拿到placeOrderItem
		TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
		itemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
			throw new Exception("订单明细为null");
		}
		BigDecimal price = new BigDecimal(0);
		//拿到销售计划场地Id
		for(TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			if (PlaceConstants.ORDER_USE_BILLING == tbBizPlaceOrderItem.getUseType().byteValue()
					|| PlaceConstants.ORDER_USE_BLOCK_BOOKING == tbBizPlaceOrderItem.getUseType().byteValue()
					|| PlaceConstants.ORDER_USE_APP_BILLING == tbBizPlaceOrderItem.getUseType().byteValue()){
				//to do other .
			} else {
				throw new BizException("只支持场地订单预订再支付");
			}
			price = price.add(tbBizPlaceOrderItem.getSalePrice());
		}

		//修改订单
		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
		org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrder,newTbBizPlaceOrder);
		//修改取消订单状态
		newTbBizPlaceOrder.setId(tbBizPlaceOrder.getId());
		newTbBizPlaceOrder.setPlaceOrderId(reqPlaceOrderId);
		newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
		newTbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
		newTbBizPlaceOrder.setPaymentTime(new Date());
		newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		newTbBizPlaceOrder.setDescrible(memo);
		newTbBizPlaceOrder.setExpression(expression);
		newTbBizPlaceOrder.setHandAdjustAmount(receivedAmount1.subtract(price));
		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
			tbBizPlaceOrder.setIsType(PlaceConstants.YES);
		}else{
			tbBizPlaceOrder.setIsType(PlaceConstants.NO);
		}
		TbBizPlaceOrderExample updateOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria updateOrderCriteria = updateOrderExample.createCriteria();
		updateOrderCriteria.andPlaceOrderIdEqualTo(reqPlaceOrderId);
		updateOrderCriteria.andOrderStatusEqualTo(PlaceConstants.ORDER_PREPAY_STATUS);
		updateOrderCriteria.andPayStatusEqualTo(PlaceConstants.NOT_PAY_STATUS);
		TbBizPlaceOrder updateOrder = new TbBizPlaceOrder();
		BeanUtils.copyProperties(newTbBizPlaceOrder,updateOrder);
		updateOrder.setId(null);//防止主键冲突
		if (this.tbBizPlaceOrderMapper.updateByExampleSelective(updateOrder,updateOrderExample) != 1){
			throw new Exception("订单状态已更新");
		}

		//订单明细
		List<TbBizPlaceOrderItem> newTbBizPlaceOrderItemList = new ArrayList<TbBizPlaceOrderItem>();
		org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrderItems,newTbBizPlaceOrderItemList);
		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(receivedAmount1,tbBizPlaceOrderItems,price);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
			tbBizPlaceOrderItemMapper.updateByPrimaryKeySelective(item);
		}

		//修改销售计划
		placeBillingUpdatePlaceUnitSalePlanPlus(adjustTbBizPlaceOrderItems);

		//添加会员预订后支付
		//获取会员卡
		TbBizPlaceMemberOpHistoryExample example1 = new TbBizPlaceMemberOpHistoryExample();
		TbBizPlaceMemberOpHistoryExample.Criteria criteria = example1.createCriteria();
		//包场根据父订单号  取会员卡交易历史
		if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
			TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrder.getParentId());
			criteria.andOrderNoEqualTo(tbBizPlacePrivateOrder.getPlaceOrderId());
		} else {
			criteria.andOrderNoEqualTo(reqPlaceOrderId);
		}
		TbBizPlaceMemberCard tbBizPlaceMemberCard = new TbBizPlaceMemberCard();

		List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example1);
		APIResponse payItemsResponse = this.shoppingCart2PayItem(adminPayType,adjustTbBizPlaceOrderItems,reqPlaceOrderId);
		if (!payItemsResponse.isRet()){
			throw new BizException("生成支付明细异常-1");
		}
		List<TbBizPlacePayItem> tbBizPlacePayItems = (List<TbBizPlacePayItem>)payItemsResponse.getData();
		if (CollectionUtils.isEmpty(tbBizPlacePayItems)){
			throw new BizException("生成支付明细异常-2");
		}
		//重新计算 优惠 金额
		HashMap orderMap = new HashMap();
		orderMap.put("order",newTbBizPlaceOrder);
		orderMap.put("items",adjustTbBizPlaceOrderItems);
		orderMap.put("pays",tbBizPlacePayItems);

		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
			logger.debug("非会员订单");

			//修改支付明细
			for (TbBizPlacePayItem tbBizPlacePayItem1 : tbBizPlacePayItems){
				tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem1);
			}

//			//散客只存在改价情况
//			if (!org.springframework.util.StringUtils.isEmpty(newTbBizPlaceOrder.getHandAdjustAmount())
//					&& newTbBizPlaceOrder.getHandAdjustAmount().compareTo(BigDecimal.ZERO) != 0){
//
//				orderMap.put("discount",null);
//
//			}

		}else{
			String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
			if(org.springframework.util.StringUtils.isEmpty(innerCardNo)){
				throw new Exception("流水会员卡号为空");
			}
			TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
			TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
			tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo)
					.andIsDeleteEqualTo(PlaceConstants.NO).andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
			List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
			if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceMemberCardList)){
				throw new Exception("无效会员卡");
			}
			tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
			//修改支付明细
			for (TbBizPlacePayItem tbBizPlacePayItem1 : tbBizPlacePayItems){
				if (null != tbBizPlaceMemberCard
						&& tbBizPlaceMemberCard.getIsOldMember() == Constants.BYTE_ONE
						&& !PlaceConstants.PLACE_ADMIN_PAY_WAYS_GIVE.equals(tbBizPlacePayItem1.getPayType().toString())){
					tbBizPlacePayItem1.setPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
					tbBizPlacePayItem1.setAdminPayType(PayTypeEnum.getEnum(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS)).getUnifiedId());
				}
				tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem1);
			}

			//优惠明细
			List<TbBizPlaceOrderDiscountItem> discountItemList = this.createDiscountItemByMemberCard(adjustTbBizPlaceOrderItems,tbBizPlaceMemberCard);

			orderMap.put("order",newTbBizPlaceOrder);
			orderMap.put("items",adjustTbBizPlaceOrderItems);
			orderMap.put("pays",tbBizPlacePayItems);
			orderMap.put("discount",discountItemList);


			BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
			BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
			BigDecimal zeroAmount = new BigDecimal(0);
			if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE){//储值卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount1));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount1.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount1.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("余额不足");
						}
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT){//折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount1));
					}
					else{
						throw new Exception("余额不足");
					}
				}
			}
			else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT){//储值折扣卡
				//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
				if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receivedAmount1)){
					//会员卡上的本金大于等于消费金额
					if (initAmount.doubleValue() >= receivedAmount1.doubleValue()){
						tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receivedAmount1));
					}
					else{
						//会员卡上的本金+赠送金额大于等于消费金额
						if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount1.doubleValue()){
							BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount1.subtract(initAmount));
							tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
							tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
						}else{
							throw new Exception("余额不足");
						}
					}
				}
			}
			tbBizPlaceMemberCard.setUpdateTime(new Date());
			if (tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard) != 1){
				throw new Exception("更新会员卡失败");
			}

			TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
			tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
			tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
			tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
			tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
			tbBizPlaceMemberOpHistory.setAmount(receivedAmount1);
			tbBizPlaceMemberOpHistory.setCreateTime(new Date());
			tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
			tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
			tbBizPlaceMemberOpHistory.setOrderNo(reqPlaceOrderId);
			tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName()+"支付");
			tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
			tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
			tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
			tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
			tbBizPlaceMemberOpHistory.setMemo(memo);
			tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
			tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
			tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
			tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
			tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
			tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
			tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
			tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
			tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());
			tbBizPlaceMemberOpHistory.setPayType(adminPayType);
			tbBizPlaceMemberOpHistory.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			//开单做更新处理
			if (!tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
				if (tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKeySelective(tbBizPlaceMemberOpHistory) != 1){
					throw new Exception("修改会员操作明细失败");
				}
			} else {
				//包场子订单按照子订单写入操作明细
				//退款生成订单号
				if (tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory) != 1){
					throw new Exception("插入会员操作明细失败");
				}
				//父订单状态同步
				checkBlockOrder(tbBizPlaceOrder, newTbBizPlaceOrder.getOrderStatus(), receivedAmount1);
			}
		}

		//计算后优惠明细
		Map calcOrderMap = this.calcOrderInfo(orderMap);
		List<TbBizPlaceOrderDiscountItem> calcDiscountList = (List<TbBizPlaceOrderDiscountItem>)MapUtils.getObject(calcOrderMap,"discount");
		if (!org.apache.commons.collections.CollectionUtils.isEmpty(calcDiscountList)){
			//如果不存在优惠信息插入，如果存在则更新
			TbBizPlaceOrderDiscountItemExample tbBizPlaceOrderDiscountItemExample = new TbBizPlaceOrderDiscountItemExample();
			tbBizPlaceOrderDiscountItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrders.get(0).getPlaceOrderId());
			List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList = tbBizPlaceOrderDiscountItemMapper.selectByExample(tbBizPlaceOrderDiscountItemExample);
			if (org.apache.commons.collections.CollectionUtils.isEmpty(tbBizPlaceOrderDiscountItemList)){
				for (TbBizPlaceOrderDiscountItem calcDiscountItem : calcDiscountList){
					tbBizPlaceOrderDiscountItemMapper.insertSelective(calcDiscountItem);
				}
			} else {
				for (TbBizPlaceOrderDiscountItem calcDiscountItem : calcDiscountList){
					for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : tbBizPlaceOrderDiscountItemList){
						if (calcDiscountItem.getOrderItemUuid().equals(tbBizPlaceOrderDiscountItem.getOrderItemUuid())){
							TbBizPlaceOrderDiscountItemExample tbBizPlaceOrderDiscountItemExample1 = new TbBizPlaceOrderDiscountItemExample();
							TbBizPlaceOrderDiscountItemExample.Criteria tbBizPlaceOrderDiscountItemCriteria1 = tbBizPlaceOrderDiscountItemExample1.createCriteria();
							tbBizPlaceOrderDiscountItemCriteria1.andPlaceOrderIdEqualTo(tbBizPlaceOrders.get(0).getPlaceOrderId());
							tbBizPlaceOrderDiscountItemCriteria1.andOrderItemUuidEqualTo(tbBizPlaceOrderDiscountItem.getOrderItemUuid());

							BeanUtils.copyProperties(calcDiscountItem,tbBizPlaceOrderDiscountItem);
							tbBizPlaceOrderDiscountItem.setId(null);//防止主键冲突
							tbBizPlaceOrderDiscountItemMapper.updateByExampleSelective(tbBizPlaceOrderDiscountItem,tbBizPlaceOrderDiscountItemExample1);
						}
					}
				}
			}
		}

		//插入支付流水
		List<ReqOrderHistory> reqOrderHistoryList = placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(newTbBizPlaceOrder,adjustTbBizPlaceOrderItems,(byte)0,(byte)0,tbBizPlaceMemberCard);
		try {
			placeOrderUtilService.shoppingCartOrderInsertOrderHistory(reqOrderHistoryList);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("生成支付流水异常");
		}

		PlacePrintVo placePrintVo = new PlacePrintVo();
		placePrintVo.setPlaceOrderId(reqPlaceOrderId);
		placePrintVo.setBusinessType(tbBizPlaceOrders.get(0).getUseType());
		if (isMember){
			placePrintVo.setIsMember(PlaceConstants.YES);
		} else {
			placePrintVo.setIsMember(PlaceConstants.NO);
		}
		return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
	}

	/**
	 * 购物车预订再支付 -- 扫码枪
	 * @param placeOrderId
	 * @param adminPayType
	 * @param receivedAmount
	 * @param memo
	 * @param expression
     * @return
     */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public TbBizPlaceOrder getTbBizPlaceOrderByOrderNoForShoppingCart(String placeOrderId,Integer adminPayType,String receivedAmount,String memo,String expression) throws Exception{
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrders)){
			return null;
		}
		if (tbBizPlaceOrders.get(0).getOrderStatus() > 1){
			throw new BizException("订单状态已更新,无法支付！");
		}
		if (!tbBizPlaceOrders.get(0).getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
			throw new BizException("不支持该订单类型再次支付");
		}
		TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
		tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrders.get(0).getPlaceOrderId());
		List<TbBizPlacePayItem> tbBizPlacePayItems = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);

		TbBizPlaceOrderDiscountItemExample tbBizPlaceOrderDiscountItemExample = new TbBizPlaceOrderDiscountItemExample();
		tbBizPlaceOrderDiscountItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrders.get(0).getPlaceOrderId());
		List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList = tbBizPlaceOrderDiscountItemMapper.selectByExample(tbBizPlaceOrderDiscountItemExample);

		BigDecimal payAmount = new BigDecimal(receivedAmount);

		if (!org.apache.commons.collections.CollectionUtils.isEmpty(tbBizPlacePayItems)){
			//由非对公转账切换到对公转账 需要提交审核
			if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(tbBizPlacePayItems.get(0).getPayType().toString())
					&& PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(adminPayType.toString())){
				// TODO: 2017/5/10 提交审核
				throw new BizException("订单已提交财务审核！");
			}
		}

		//订单明细
		//根据placeOrderId拿到placeOrderItem
		TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
		itemExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
			throw new BizException("订单明细为null");
		}
		BigDecimal price = new BigDecimal(0);
		for(TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			price = price.add(tbBizPlaceOrderItem.getSalePrice());
		}

		tbBizPlaceOrders.get(0).setHandAdjustAmount((org.springframework.util.StringUtils.isEmpty(tbBizPlaceOrders.get(0).getHandAdjustAmount())?BigDecimal.ZERO:tbBizPlaceOrders.get(0).getHandAdjustAmount())
				.add(payAmount.subtract(price)));
		tbBizPlaceOrders.get(0).setExpression(expression);
		tbBizPlaceOrders.get(0).setDescrible(memo);
		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
			tbBizPlaceOrders.get(0).setIsType(PlaceConstants.YES);
		}

		List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(payAmount,tbBizPlaceOrderItems,price);

		APIResponse payItemsResponse = this.shoppingCart2PayItem(adminPayType,adjustTbBizPlaceOrderItems,tbBizPlaceOrders.get(0).getPlaceOrderId());
		if (!payItemsResponse.isRet()){
			throw new BizException("生成支付明细异常-1");
		}
		List<TbBizPlacePayItem> adjustPayItems = (List<TbBizPlacePayItem>)payItemsResponse.getData();
		if (CollectionUtils.isEmpty(adjustPayItems)){
			throw new BizException("生成支付明细异常-2");
		}
		//重新计算 优惠 金额
		HashMap orderMap = new HashMap();
		orderMap.put("order",tbBizPlaceOrders.get(0));
		orderMap.put("items",adjustTbBizPlaceOrderItems);
		orderMap.put("pays",adjustPayItems);
		
		 
		tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceOrders.get(0),tbBizPlaceOrderExample);
		for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
			tbBizPlaceOrderItemMapper.updateByPrimaryKeySelective(item);
		}
		
		//add pos支付特殊处理
		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
			orderMap.remove("pays");
		}
		if (!org.apache.commons.collections.CollectionUtils.isEmpty(adjustPayItems)){
			//如果不存在支付信息插入，如果存在则更新
			if (org.apache.commons.collections.CollectionUtils.isEmpty(tbBizPlacePayItems)){
				for (TbBizPlacePayItem adjPayItem : adjustPayItems){
					tbBizPlacePayItemMapper.insertSelective(adjPayItem);
				}
			} else {
				for (TbBizPlacePayItem adjPayItem : adjustPayItems){
					for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItems){
						if (adjPayItem.getOrderItemUuid().equals(tbBizPlacePayItem.getOrderItemUuid())){
							TbBizPlacePayItemExample tbBizPlacePayItemExample1 = new TbBizPlacePayItemExample();
							TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria1 = tbBizPlacePayItemExample1.createCriteria();
							tbBizPlacePayItemCriteria1.andPlaceOrderIdEqualTo(tbBizPlaceOrders.get(0).getPlaceOrderId());
							tbBizPlacePayItemCriteria1.andOrderItemUuidEqualTo(tbBizPlacePayItem.getOrderItemUuid());

							BeanUtils.copyProperties(adjPayItem,tbBizPlacePayItem);
							tbBizPlacePayItem.setId(null);//防止主键冲突
							tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,tbBizPlacePayItemExample1);
						}
					}
				}
			}
		}
		//计算后优惠明细
		Map calcOrderMap = this.calcOrderInfo(orderMap);
		List<TbBizPlaceOrderDiscountItem> calcDiscountList = (List<TbBizPlaceOrderDiscountItem>)MapUtils.getObject(calcOrderMap,"discount");
		if (!org.apache.commons.collections.CollectionUtils.isEmpty(calcDiscountList)){
			//如果不存在优惠信息插入，如果存在则更新
			if (org.apache.commons.collections.CollectionUtils.isEmpty(tbBizPlaceOrderDiscountItemList)){
				for (TbBizPlaceOrderDiscountItem calcDiscountItem : calcDiscountList){
					tbBizPlaceOrderDiscountItemMapper.insertSelective(calcDiscountItem);
				}
			} else {
				for (TbBizPlaceOrderDiscountItem calcDiscountItem : calcDiscountList){
					for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : tbBizPlaceOrderDiscountItemList){
						if (calcDiscountItem.getOrderItemUuid().equals(tbBizPlaceOrderDiscountItem.getOrderItemUuid())){
							TbBizPlaceOrderDiscountItemExample tbBizPlaceOrderDiscountItemExample1 = new TbBizPlaceOrderDiscountItemExample();
							TbBizPlaceOrderDiscountItemExample.Criteria tbBizPlaceOrderDiscountItemCriteria1 = tbBizPlaceOrderDiscountItemExample1.createCriteria();
							tbBizPlaceOrderDiscountItemCriteria1.andPlaceOrderIdEqualTo(tbBizPlaceOrders.get(0).getPlaceOrderId());
							tbBizPlaceOrderDiscountItemCriteria1.andOrderItemUuidEqualTo(tbBizPlaceOrderDiscountItem.getOrderItemUuid());

							BeanUtils.copyProperties(calcDiscountItem,tbBizPlaceOrderDiscountItem);
							tbBizPlaceOrderDiscountItem.setId(null);//防止主键冲突
							tbBizPlaceOrderDiscountItemMapper.updateByExampleSelective(tbBizPlaceOrderDiscountItem,tbBizPlaceOrderDiscountItemExample1);
						}
					}
				}
			}
		}

		return tbBizPlaceOrders.get(0);
	}

	/**
	 * 购物车下单入库
	 * @param reqShoppingCart
	 * @return
     */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public APIResponse<?> shoppingCart(ReqShoppingCart reqShoppingCart) throws Exception{
		boolean isScanPayFlag = false;

		if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getAdminPayType())){
			if(MerchantClientPayType.getMatchScanPayType().containsKey(reqShoppingCart.getAdminPayType().toString())){//扫码支付方式匹配 update by tim
				isScanPayFlag = true;
			}
		}

		APIResponse orderInfoResponse = this.createShoppingCartOrderInfo(reqShoppingCart,true);
		if (!orderInfoResponse.isRet()){
			return orderInfoResponse;
		}
		Map orderInfoMap = (Map)orderInfoResponse.getData();
		TbBizPlaceOrder tbBizPlaceOrder = (TbBizPlaceOrder) MapUtils.getObject(orderInfoMap,"order");
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = (List<TbBizPlaceOrderItem>) MapUtils.getObject(orderInfoMap,"items");
		List<TbBizPlacePayItem> tbBizPlacePayItemList = (List<TbBizPlacePayItem>) MapUtils.getObject(orderInfoMap,"pays");
		List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList = (List<TbBizPlaceOrderDiscountItem>) MapUtils.getObject(orderInfoMap,"discount");
		TbBizPlaceMemberCard modifyCard = (TbBizPlaceMemberCard)MapUtils.getObject(orderInfoMap,"card") ;
		TbBizPlaceMemberOpHistory history = (TbBizPlaceMemberOpHistory)MapUtils.getObject(orderInfoMap,"history") ;
		ReqPlaceOrderListVo reqPlaceOrderListVo = (ReqPlaceOrderListVo)MapUtils.getObject(orderInfoMap,"reqPlaceOrderListVo");
		
		//预订情况
		/**
		 * reqShoppingCart.pay_status == 0
		 * 1.保存订单
		 * 2.保存订单明细
		 * 3.保存订单优惠
		 * 4.保存会员流水
		 * 5.场地库存锁定
		 */
		if (reqShoppingCart.getPayStatus().byteValue() == 0){
			this.shoppingCartBook(tbBizPlaceOrder,tbBizPlaceOrderItemList,tbBizPlaceOrderDiscountItemList,history,reqPlaceOrderListVo);
			return APIResponse.returnSuccess(this.shoppingCartPrintTicket(reqShoppingCart,tbBizPlaceOrder));
		}
		
		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqShoppingCart.getAdminPayType().toString())){
			tbBizPlaceOrder.setIsType(PlaceConstants.YES);
			tbBizPlacePayItemList.clear();
		}else{
			tbBizPlaceOrder.setIsType(PlaceConstants.NO);
		}
		//直接支付情况
		/**
		 * reqShoppingCart.pay_status == 1 && reqShoppingCart.getAdminPayType() != null && !isScanPayFlag
		 * 1.填充订单信息保存订单
		 * 2.填充订单明细保存订单明细
		 * 3.保存支付明细
		 * 4.填充优惠明细保存优惠明细
		 * 5.是会员扣减会员卡，会员流水置有效
		 * 6.插入支付流水
		 * 7.减库存
		 */
		if (reqShoppingCart.getPayStatus().byteValue() == 1
				&& !org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getAdminPayType())
				&& !isScanPayFlag){
			
			this.shoppingCartPay(tbBizPlaceOrder,tbBizPlaceOrderItemList,tbBizPlacePayItemList,tbBizPlaceOrderDiscountItemList,modifyCard,history,reqPlaceOrderListVo);
			return APIResponse.returnSuccess(this.shoppingCartPrintTicket(reqShoppingCart,tbBizPlaceOrder));
		}

		/**
		 * 购物车扫码枪支付
		 */
		if (reqShoppingCart.getPayStatus().byteValue() == 1 && isScanPayFlag){
			if (org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getReceivedAmount())){
				return APIResponse.returnFail("scan pay must input receive amount");
			}
			
			this.shoppingCartPayForScanPay(tbBizPlaceOrder,tbBizPlaceOrderItemList,tbBizPlacePayItemList,tbBizPlaceOrderDiscountItemList);

			PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();
			placeScanOrderPayVo.setReceivedAmount(new BigDecimal(reqShoppingCart.getReceivedAmount()));
			placeScanOrderPayVo.setAdminPayType(reqShoppingCart.getAdminPayType().toString());
			placeScanOrderPayVo.setScanCode(reqShoppingCart.getScanCode());
			placeScanOrderPayVo.setTbBizPlaceOrder(tbBizPlaceOrder);
			placeScanOrderPayVo.setTbBizPlacePrivateOrder(null);
			return scanOrderPay(placeScanOrderPayVo);
		}

		return APIResponse.returnFail("操作失败");
	}

	/**
	 * 购物车直接支付db操作
	 *
	 *  * reqShoppingCart.pay_status == 1 && reqShoppingCart.getAdminPayType() != null && !isScanPayFlag
	 * 1.填充订单信息保存订单
	 * 2.填充订单明细保存订单明细
	 * 3.保存支付明细
	 * 4.填充优惠明细保存优惠明细
	 * 5.是会员扣减会员卡，会员流水置有效
	 * 6.插入支付流水
	 * 7.减库存
	 * @param tbBizPlaceOrder
	 * @param tbBizPlaceOrderItemList
	 * @param tbBizPlacePayItemList
	 * @param tbBizPlaceOrderDiscountItemList
	 * @param modifyCard
	 * @param history
     * @param reqPlaceOrderListVo
     */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public void shoppingCartPay(TbBizPlaceOrder tbBizPlaceOrder,
								List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList,
								List<TbBizPlacePayItem> tbBizPlacePayItemList,
								List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList,
								TbBizPlaceMemberCard modifyCard,
								TbBizPlaceMemberOpHistory history,
								ReqPlaceOrderListVo reqPlaceOrderListVo) throws Exception{
		if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceOrder)){
			tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
			tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
			//填充支付时间
			tbBizPlaceOrder.setPaymentTime(new Date());
			tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder);
		}
		//插入订单明细
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
				tbBizPlaceOrderItem.setStatus(PlaceConstants.ORDER_PAYED_STATUS.intValue());
				tbBizPlaceOrderItemMapper.insertSelective(tbBizPlaceOrderItem);
			}
		}
		//插入支付明细
		if (!CollectionUtils.isEmpty(tbBizPlacePayItemList)){
			for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList){
				tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
			}
		}
		//插入优惠明细
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderDiscountItemList)){
			for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : tbBizPlaceOrderDiscountItemList){
				tbBizPlaceOrderDiscountItem.setStatus(PlaceConstants.ORDER_PAYED_STATUS.intValue());
				tbBizPlaceOrderDiscountItemMapper.insertSelective(tbBizPlaceOrderDiscountItem);
			}
		}
		//插入会员流水 ，扣减会员卡
		if (!org.springframework.util.StringUtils.isEmpty(history)) {
			tbBizPlaceMemberCardMapper.updateByPrimaryKey(modifyCard);
			history.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
			tbBizPlaceMemberOpHistoryMapper.insertSelective(history);
		}
		//插入支付流水
		List<ReqOrderHistory> reqOrderHistoryList = placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(tbBizPlaceOrder,tbBizPlaceOrderItemList,(byte)0,(byte)0,modifyCard);
		if (!CollectionUtils.isEmpty(reqOrderHistoryList)){
			try {
				placeOrderUtilService.shoppingCartOrderInsertOrderHistory(reqOrderHistoryList);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("生成支付流水异常");
			}
		}
		//场地减库存
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)) {
			this.placeBillingUpdatePlaceUnitSalePlanPlus(tbBizPlaceOrderItemList);
		}
		//商品减库存
		this.shoppingCartUpdateGoodsInventory(tbBizPlaceOrderItemList,tbBizPlaceOrder);
		//门票统计
		try {
			this.shoppingCartTicketStatistics(tbBizPlaceOrder.getPlaceId(), tbBizPlaceOrderItemList);
		}catch (Exception e){
			throw new BizException("门票统计异常.");
		}
	}

	/**
	 * 购物车扫码支付db操作
	 *
	 *  reqShoppingCart.getPayStatus().byteValue() == 1 && isScanPayFlag
	 * 1.填充订单信息保存订单
	 * 2.填充订单明细保存订单明细
	 * 3.保存支付明细
	 * 4.填充优惠明细保存优惠明细
	 * 6.插入支付流水
	 * @param tbBizPlaceOrder
	 * @param tbBizPlaceOrderItemList
	 * @param tbBizPlacePayItemList
	 * @param tbBizPlaceOrderDiscountItemList
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public void shoppingCartPayForScanPay(TbBizPlaceOrder tbBizPlaceOrder,
								List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList,
								List<TbBizPlacePayItem> tbBizPlacePayItemList,
								List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList) throws Exception{
		if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceOrder)){
			tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
			tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);

			tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder);
		}
		//插入订单明细
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
				tbBizPlaceOrderItem.setStatus(PlaceConstants.ORDER_PREPAY_STATUS.intValue());
				tbBizPlaceOrderItemMapper.insertSelective(tbBizPlaceOrderItem);
			}
		}
		//插入支付明细
		if (!CollectionUtils.isEmpty(tbBizPlacePayItemList)){
			for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList){
				tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);
			}
		}
		//插入优惠明细
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderDiscountItemList)){
			for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : tbBizPlaceOrderDiscountItemList){
				tbBizPlaceOrderDiscountItem.setStatus(PlaceConstants.ORDER_PREPAY_STATUS.intValue());
				tbBizPlaceOrderDiscountItemMapper.insertSelective(tbBizPlaceOrderDiscountItem);
			}
		}
	}

	/**
	 * 购物车预订db操作
	 *
	 *  reqShoppingCart.pay_status == 0
	 * 1.保存订单
	 * 2.保存订单明细
	 * 3.保存订单优惠
	 * 4.保存会员流水
	 * 5.场地库存锁定
	 * @param tbBizPlaceOrder
	 * @param tbBizPlaceOrderItemList
	 * @param tbBizPlaceOrderDiscountItemList
	 * @param history
	 * @param reqPlaceOrderListVo
     */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	public void shoppingCartBook(TbBizPlaceOrder tbBizPlaceOrder,
								  List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList,
								  List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList,
								  TbBizPlaceMemberOpHistory history,
								  ReqPlaceOrderListVo reqPlaceOrderListVo) throws Exception{
		//插入订单
		if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceOrder)){
			tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder);
		}
		//插入订单明细
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
				tbBizPlaceOrderItemMapper.insertSelective(tbBizPlaceOrderItem);
			}
		}
		//插入优惠明细
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderDiscountItemList)){
			for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : tbBizPlaceOrderDiscountItemList){
				tbBizPlaceOrderDiscountItemMapper.insertSelective(tbBizPlaceOrderDiscountItem);
			}
		}
		//插入会员流水
		if (!org.springframework.util.StringUtils.isEmpty(history)) {
			tbBizPlaceMemberOpHistoryMapper.insertSelective(history);
		}
		//场地锁库存
		if (!org.springframework.util.StringUtils.isEmpty(reqPlaceOrderListVo)){
			try {
				lockTbBizPlaceUnitSalePlanExPlus(reqPlaceOrderListVo);
			} catch (Exception e){
				throw e;
			}
		}
	}

	/**
	 * 购物车打印小票
	 * @param reqShoppingCart
	 * @param tbBizPlaceOrder
     * @return
     */
	private RespPlacePrintInfo shoppingCartPrintTicket(ReqShoppingCart reqShoppingCart,TbBizPlaceOrder tbBizPlaceOrder){
		PlacePrintVo placePrintVo = new PlacePrintVo();
		if (org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getMemberCardId())){
			placePrintVo.setIsMember(PlaceConstants.NO);
		} else {
			placePrintVo.setIsMember(PlaceConstants.YES);
		}
		placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_SHOPPING_CART);
		placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
		return placeOrderUtilService.getPrintOrderInfo(placePrintVo);
	}
	/**
	 * 小商品减库存
	 * @param tbBizPlaceOrderItemList
     */
	public void shoppingCartUpdateGoodsInventory(List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList,TbBizPlaceOrder tbBizPlaceOrder) {
		if (CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			return;
		}
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
			if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
				TbBizPlaceGoods goodsVo=tbBizPlaceGoodsMapper.selectByPrimaryKey(tbBizPlaceOrderItem.getGoodsId());
				int initInventory = goodsVo.getInventory().intValue();
				int counts=initInventory - tbBizPlaceOrderItem.getTotalGoodsCount().intValue();

				Map paraMap = new HashMap();
				paraMap.put("goodsId",tbBizPlaceOrderItem.getGoodsId());
				paraMap.put("goodsCounts",tbBizPlaceOrderItem.getTotalGoodsCount());
				int result = vPlaceGoodsMapper.subtractGoodsInventory(paraMap);
				if (result != 1){
					throw new BizException(goodsVo.getName()+"库存不足");
				}

				ReqPlaceGoodsVo reqPlaceGoodsVo = new ReqPlaceGoodsVo();
				reqPlaceGoodsVo.setPlaceId(tbBizPlaceOrder.getPlaceId());
				reqPlaceGoodsVo.setGoodsId(goodsVo.getGoodsId());
				reqPlaceGoodsVo.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
				reqPlaceGoodsVo.setOperateCount(tbBizPlaceOrderItem.getTotalGoodsCount().intValue());
				reqPlaceGoodsVo.setOpBeforeCount(initInventory);
				reqPlaceGoodsVo.setOpAfterCount(counts);
				if (tbBizPlaceOrderItem.getIsGive().intValue() == 1){
					reqPlaceGoodsVo.setOperateType(5);//赠送
				} else {
					reqPlaceGoodsVo.setOperateType(1);//售出
				}
				reqPlaceGoodsVo.setUid(tbBizPlaceOrder.getCreateUid());
				reqPlaceGoodsVo.setRemark(tbBizPlaceOrder.getDescrible());
				placeGoodsService.insertGoodsOperateRecord(reqPlaceGoodsVo);
			}
		}
	}

	/**
	 * 门票统计
	 * @param placeId
	 * @param tbBizPlaceOrderItemList
     */
	public void shoppingCartTicketStatistics(Integer placeId,List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList) throws Exception{
		if (CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			return;
		}
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = new ArrayList<>();
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
			if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
				tbBizPlaceOrderItems.add(tbBizPlaceOrderItem);
			}
		}

		BigDecimal singlePrice = new BigDecimal(0);
		Map priceMap = new HashMap();
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			singlePrice = item.getSalePrice();
			if (!priceMap.containsKey(item.getUnitSalePlanId())){
				priceMap.put(item.getGoodsId(),singlePrice);
			}
		}
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			TbPlaceTicketStatistics tbPlaceTicketStatistics1 = new TbPlaceTicketStatistics();
			tbPlaceTicketStatistics1.setUpdateTime(new Date());
			tbPlaceTicketStatistics1.setTicketId(tbBizPlaceOrderItem.getGoodsId());
			tbPlaceTicketStatistics1.setPlaceId(placeId);
			tbPlaceTicketStatistics1.setTotal(tbBizPlaceOrderItem.getTicketCount());
			tbPlaceTicketStatistics1.setSalePrice((BigDecimal) priceMap.get(tbBizPlaceOrderItem.getGoodsId()));
			tbPlaceTicketStatistics1.setCreateTime(new Date());
			tbPlaceTicketStatistics1.setSaleDate(new Date());
			try{
				int flag = tbPlaceTicketStatisticsMapper.insert(tbPlaceTicketStatistics1);
				if (flag == 1){
					logger.debug("========================新增门票统计成功。");
				}
			}catch (Exception e){
				//更新门票数
				TbPlaceTicketStatisticsExample tbPlaceTicketStatisticsExample = new TbPlaceTicketStatisticsExample();
				TbPlaceTicketStatisticsExample.Criteria tbPlaceTicketStatisticsCriteria = tbPlaceTicketStatisticsExample.createCriteria();
				tbPlaceTicketStatisticsCriteria.andTicketIdEqualTo(tbBizPlaceOrderItem.getGoodsId());
				tbPlaceTicketStatisticsCriteria.andSaleDateEqualTo(new Date());
				tbPlaceTicketStatisticsCriteria.andSalePriceEqualTo((BigDecimal) priceMap.get(tbBizPlaceOrderItem.getGoodsId()));
				tbPlaceTicketStatisticsExample.setOrderByClause(" id for update ");
				List<TbPlaceTicketStatistics> tbPlaceTicketStatisticses2 = tbPlaceTicketStatisticsMapper
						.selectByExample(tbPlaceTicketStatisticsExample);
				if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbPlaceTicketStatisticses2)){//存在，更新
					TbPlaceTicketStatistics tbPlaceTicketStatistics3 = new TbPlaceTicketStatistics();
					tbPlaceTicketStatistics3.setId(tbPlaceTicketStatisticses2.get(0).getId());
					tbPlaceTicketStatistics3.setUpdateTime(new Date());
					tbPlaceTicketStatistics3.setTotal(tbPlaceTicketStatisticses2.get(0).getTotal()+tbBizPlaceOrderItem.getTotalGoodsCount());//门票+
					tbPlaceTicketStatistics3.setSalePrice((BigDecimal) priceMap.get(tbBizPlaceOrderItem.getGoodsId()));
					int flag = tbPlaceTicketStatisticsMapper.updateByPrimaryKeySelective(tbPlaceTicketStatistics3);
					if (flag == 1){
						logger.debug("========================更新门票统计成功。");
					}
				}
			}
		}
		logger.debug("========================门票统计结束。");
	}
	/**
	 * 购物车生成订单信息
	 *
	 * @param reqShoppingCart
	 * @param reqShoppingCart
	 * @return
	 */
	public APIResponse<?> createShoppingCartOrderInfo(ReqShoppingCart reqShoppingCart,final boolean checkBilling) {
		if (reqShoppingCart == null){
			return APIResponse.returnFail("购物车为空.");
		}
		if (reqShoppingCart.getCreateUid() == null){
			return APIResponse.returnFail("createUid必传");
		}
		if (reqShoppingCart.getPlaceId() == null){
			return APIResponse.returnFail("placeId必传");
		}
		if (checkBilling){
			if (reqShoppingCart.getPayStatus() == null){
				return APIResponse.returnFail("payStatus必传");
			}
			//如果是预定将实付金额置为0
			if (reqShoppingCart.getPayStatus().intValue() == 0){
				reqShoppingCart.setReceivedAmount(null);
			}
		}


		Map orderInfo = new HashMap();
		//生成订单号
		String orderId = iBaseService.getBizOrderId(reqShoppingCart.getCreateUid());

		//生成订单
		TbBizPlaceOrder tbBizPlaceOrder = this.shoppingCart2Order(reqShoppingCart,orderId);
		orderInfo.put("order", tbBizPlaceOrder);

		//生成订单明细
		APIResponse<?> allItemResponse = this.shoppingCart2OrderItem(reqShoppingCart,orderId,checkBilling);
		if (!allItemResponse.isRet()){
			return allItemResponse;
		}
		Map orderItemsReqPlaceOrderListVoMap = (Map)allItemResponse.getData();
		List<TbBizPlaceOrderItem> allOrderItemList = (List<TbBizPlaceOrderItem>)MapUtils.getObject(orderItemsReqPlaceOrderListVoMap,"tbBizPlaceOrderItemList");
		ReqPlaceOrderListVo reqPlaceOrderListVo = (ReqPlaceOrderListVo)MapUtils.getObject(orderItemsReqPlaceOrderListVoMap,"reqPlaceOrderListVo");
		orderInfo.put("items", allOrderItemList);
		orderInfo.put("reqPlaceOrderListVo",reqPlaceOrderListVo);

		if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getMemberCardId())){//会员
			//校验会员卡是否支持政策
			APIResponse checkMemberCardResponse = this.checkMemberCardShoppingCartInfo(reqShoppingCart,orderInfo);
			if (!checkMemberCardResponse.isRet()){
				return checkMemberCardResponse;
			}
			TbBizPlaceMemberCard tbBizPlaceMemberCard = (TbBizPlaceMemberCard)checkMemberCardResponse.getData();

			//根据会员卡重新计算订单明细金额
			allOrderItemList = this.calcOrderItemSalePrice(reqShoppingCart,allOrderItemList,tbBizPlaceMemberCard);

			//修改成会员订单
			tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
			tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
			//下单用户
			tbBizPlaceOrder.setUid(tbBizPlaceMemberCard.getMemberUid());
			tbBizPlaceOrder.setCustomerName(reqShoppingCart.getName());
			orderInfo.put("order", tbBizPlaceOrder);

			APIResponse tbMemberInfoResponse = this.createTbMemberInfo(tbBizPlaceMemberCard, reqShoppingCart, orderId,allOrderItemList);
			if (!tbMemberInfoResponse.isRet()){
				return tbMemberInfoResponse;
			}
			Map tbMemberInfo = (Map)tbMemberInfoResponse.getData();
			TbBizPlaceMemberCard modifyCard = (TbBizPlaceMemberCard)MapUtils.getObject(tbMemberInfo,"card") ;
			TbBizPlaceMemberOpHistory history = (TbBizPlaceMemberOpHistory)MapUtils.getObject(tbMemberInfo,"history") ;
			orderInfo.put("card",modifyCard);
			orderInfo.put("history",history);

			List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList =
					this.createDiscountItemByMemberCard(allOrderItemList,tbBizPlaceMemberCard);
			orderInfo.put("discount",tbBizPlaceOrderDiscountItemList);
		} else {//散客
			//下单用户
			tbBizPlaceOrder.setUid(reqShoppingCart.getCreateUid());
			tbBizPlaceOrder.setCustomerName(StringUtils.isEmpty(reqShoppingCart.getName())?"散客":reqShoppingCart.getName());

			allOrderItemList = this.calcOrderItemSalePrice(reqShoppingCart,allOrderItemList,null);
		}
		//覆盖订单和订单明细
		orderInfo.put("items", allOrderItemList);
		orderInfo.put("order", tbBizPlaceOrder);


		if (checkBilling){
			if (reqShoppingCart.getPayStatus().intValue() != 0){
				//生成支付明细
				APIResponse<?> payItemResponse = this.shoppingCart2PayItem(reqShoppingCart.getAdminPayType(),allOrderItemList,orderId);
				if (!payItemResponse.isRet()){
					return payItemResponse;
				}
				List<TbBizPlacePayItem> tbBizPlacePayItemList = (List<TbBizPlacePayItem>)payItemResponse.getData();
				orderInfo.put("pays", tbBizPlacePayItemList);
			}
		}


		// 支付重新计算订单 [填充手动调价]
		orderInfo = this.calcOrderInfo(orderInfo);


		return APIResponse.returnSuccess(orderInfo);
	}

	/**
	 * 会员卡扣减，生成流水
	 * @param tbBizPlaceMemberCard
	 * @param reqShoppingCart
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	private APIResponse<?> createTbMemberInfo(TbBizPlaceMemberCard tbBizPlaceMemberCard, ReqShoppingCart reqShoppingCart, String orderId, List<TbBizPlaceOrderItem> allOrderItemList){
		BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount() == null ? BigDecimal.ZERO :tbBizPlaceMemberCard.getSurplusAmount();
		BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount() == null ? BigDecimal.ZERO :tbBizPlaceMemberCard.getSurplusGiveAmount();
		int initNumbers = tbBizPlaceMemberCard.getSurplusNumbers() == null ? 0 : tbBizPlaceMemberCard.getSurplusNumbers();
		BigDecimal zeroAmount = new BigDecimal(0);
		BigDecimal receiveAmount = new BigDecimal(0);
		if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getReceivedAmount())){
			receiveAmount = receiveAmount.add(new BigDecimal(reqShoppingCart.getReceivedAmount()));
		}else {
			//默认订单金额
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : allOrderItemList){
				receiveAmount = receiveAmount.add(tbBizPlaceOrderItem.getSalePrice());
			}
		}

		tbBizPlaceMemberCard.setUpdateTime(new Date());
		//会员卡余额（本金+赠送金额）是否小于应付金额
		if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE){//储值卡
			//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
			if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receiveAmount)){
				//会员卡上的本金大于等于消费金额
				if (initAmount.doubleValue() >= receiveAmount.doubleValue()){
					tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receiveAmount));
				}
				else{
					//会员卡上的本金+赠送金额大于等于消费金额
					if (initAmount.add(initGiveAmount).doubleValue() >= receiveAmount.doubleValue()){
						BigDecimal surplusGiveAmount = initGiveAmount.subtract(receiveAmount.subtract(initAmount));
						tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
						tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
					}else{
						return APIResponse.returnFail("该会员卡余额不足，请先充值！");
					}
				}
			}
		}
		else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT){//折扣卡
			//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
			if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receiveAmount)){
				//会员卡上的本金大于等于消费金额
				if (initAmount.doubleValue() >= receiveAmount.doubleValue()){
					tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receiveAmount));
				}
				else{
					return APIResponse.returnFail("该会员卡余额不足，请先充值！");
				}
			}
		}
		else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT){//储值折扣卡
			//扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
			if (!org.springframework.util.StringUtils.isEmpty(initAmount) && !org.springframework.util.StringUtils.isEmpty(receiveAmount)){
				//会员卡上的本金大于等于消费金额
				if (initAmount.doubleValue() >= receiveAmount.doubleValue()){
					tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receiveAmount));
				}
				else{
					//会员卡上的本金+赠送金额大于等于消费金额
					if (initAmount.add(initGiveAmount).doubleValue() >= receiveAmount.doubleValue()){
						BigDecimal surplusGiveAmount = initGiveAmount.subtract(receiveAmount.subtract(initAmount));
						tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
						tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
					}else{
						return APIResponse.returnFail("该会员卡余额不足，请先充值！");
					}
				}
			}
		}else if(tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER){//次卡
			List<ReqTicketSale> list = reqShoppingCart.getReqTicketPay().getTicketSaleList();
			ReqTicketSale reqTicketSale = new ReqTicketSale();
			if(list!=null){
				reqTicketSale = list.get(0);
			}
			int count = reqTicketSale.getCount();
			if(count>initNumbers){
				return APIResponse.returnFail("该会员卡余额不足，请先充值！");
			}else{
				tbBizPlaceMemberCard.setSurplusNumbers(initNumbers-count);
			}
		}

		TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
		tbBizPlaceMemberOpHistory.setCreateUid(reqShoppingCart.getCreateUid());
		tbBizPlaceMemberOpHistory.setPlaceId(reqShoppingCart.getPlaceId());
		tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
		tbBizPlaceMemberOpHistory.setAmount(initAmount.add(initGiveAmount).subtract(
				(
						(org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusAmount())?BigDecimal.ZERO:tbBizPlaceMemberCard.getSurplusAmount())
						.add(org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusGiveAmount())?BigDecimal.ZERO:tbBizPlaceMemberCard.getSurplusGiveAmount())
				)
		));
		tbBizPlaceMemberOpHistory.setCreateTime(new Date());
		tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
		tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqShoppingCart.getPlaceId()));
		tbBizPlaceMemberOpHistory.setOrderNo(orderId);
		tbBizPlaceMemberOpHistory.setOpTypeName("商家端-购物车费用");
		tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberCard.getMemberUid());
		tbBizPlaceMemberOpHistory.setUserName(reqShoppingCart.getName());
		tbBizPlaceMemberOpHistory.setMobile(reqShoppingCart.getContactInformation());
		TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqShoppingCart.getMemberCardId());
		tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
		tbBizPlaceMemberOpHistory.setMemo(reqShoppingCart.getMemo());
		tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
		tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
		tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
		tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);//无效流水
		tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
		tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
		tbBizPlaceMemberOpHistory.setOpBeforeNumbers(initNumbers);
		tbBizPlaceMemberOpHistory.setOpCardCount((org.springframework.util.StringUtils.isEmpty(initNumbers)?0:initNumbers)
				- (org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusNumbers())?0:tbBizPlaceMemberCard.getSurplusNumbers())
		);
		tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
		tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
		tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());
		tbBizPlaceMemberOpHistory.setPayType(reqShoppingCart.getAdminPayType());
		tbBizPlaceMemberOpHistory.setAdminPayType(org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getAdminPayType()) ? null:PayTypeEnum.getEnum(reqShoppingCart.getAdminPayType()).getUnifiedId());
		tbBizPlaceMemberOpHistory.setPlatform(5);//后台开单

		Map memberInfo = new HashMap();
		memberInfo.put("card",tbBizPlaceMemberCard);
		memberInfo.put("history",tbBizPlaceMemberOpHistory);

		return APIResponse.returnSuccess(memberInfo);
	}

	/**
	 * 按价格占比率均摊每个订单明细的实收价
	 * @param reqShoppingCart
	 * @param tbBizPlaceOrderItems
	 * @param tbBizPlaceMemberCard
     * @return
     */
	private List<TbBizPlaceOrderItem> calcOrderItemSalePrice(ReqShoppingCart reqShoppingCart,List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,TbBizPlaceMemberCard tbBizPlaceMemberCard) {
		BigDecimal receivedAmount = new BigDecimal(0);
		List<TbBizPlaceOrderItem> list = new ArrayList<TbBizPlaceOrderItem>();
		//下标
		int index = 0;
		//最后一个商品之前的总售卖价
		BigDecimal lastBeforeAmount = new BigDecimal(0);
		//订单金额
		BigDecimal orderAmount = new BigDecimal(0);
		BigDecimal memberOrderAmount = new BigDecimal(0);
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems){
			orderAmount = orderAmount.add(item.getOriginPrice().multiply(new BigDecimal(item.getTotalGoodsCount())));
			//门票，小商品不参与打折
			if (item.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
					|| item.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
					|| item.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
				if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getMemberCardId())) {
					memberOrderAmount = memberOrderAmount.add(item.getMemberPrice().multiply(new BigDecimal(item.getTotalGoodsCount()))
							.multiply(new BigDecimal(tbBizPlaceMemberCard.getDiscount())).divide(new BigDecimal(100)));
				} else {
					memberOrderAmount = memberOrderAmount.add(item.getMemberPrice().multiply(new BigDecimal(item.getTotalGoodsCount())));
				}
			} else {
				memberOrderAmount = memberOrderAmount.add(item.getMemberPrice().multiply(new BigDecimal(item.getTotalGoodsCount())));
			}
		}
		if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getReceivedAmount())){//支付
			receivedAmount = receivedAmount.add(new BigDecimal(reqShoppingCart.getReceivedAmount()));
		}
		else{//未支付
			if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getMemberCardId())) {
				//会员
				if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.intValue()){//次卡支付
					receivedAmount = BigDecimal.ZERO;
				} else {
					receivedAmount = memberOrderAmount;
				}
			} else {
				//散客
				receivedAmount = orderAmount;
			}
		}
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems){
			/*//赠送商品不参与计算
			if (item.getSalePrice().equals(BigDecimal.ZERO) && item.getIsGive().equals(PlaceConstants.YES)){
				continue;
			}*/
			index = index + 1;
			BigDecimal salePrice = new BigDecimal(0);
			if (!(orderAmount.compareTo(BigDecimal.ZERO)==0) || !(memberOrderAmount.compareTo(BigDecimal.ZERO)==0)){//排除不是全部赠送
				if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getMemberCardId())) {
					//会员  [门票，小商品不参与打折]
					if (item.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
							|| item.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
							|| item.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
						salePrice = ((item.getMemberPrice().multiply(new BigDecimal(tbBizPlaceMemberCard.getDiscount())).divide(new BigDecimal(100))
								.multiply(new BigDecimal(item.getTotalGoodsCount())))
								.multiply(receivedAmount))
								.divide(memberOrderAmount,2,BigDecimal.ROUND_HALF_UP);
					}else {
						if (item.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
							/************* 次卡买门票计算start  **************/
							Map<String,Object> params=new HashMap<>();
							params.put("memberCardId", tbBizPlaceMemberCard.getId());
							List<TbBizPlaceMemberCardTypeInitAmount> memberCardTypeList = posUnionPayMapper
									.selectCardTypeInitAmoutByPK(params);
							TbBizPlaceMemberCardTypeInitAmount memberCardType = null;
							if (null != memberCardTypeList && memberCardTypeList.size() > 0){
								memberCardType = memberCardTypeList.get(0);
							}
							if (memberCardType != null) {
								int cardTypeTmp=memberCardType.getCardType();
								if(cardTypeTmp == PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.intValue()){//卡类型(1:储值卡 2：折扣卡 3：储值折扣卡 4：次卡)，有以上几种，其中次卡比较特殊主要针对门票
									BigDecimal cardPrice=(memberCardType.getInitAmount().divide(new BigDecimal(memberCardType.getFrequency()),2,BigDecimal.ROUND_HALF_UP));//计算次卡单价
									salePrice = cardPrice.multiply(new BigDecimal(item.getTotalGoodsCount()));
								}else{
									salePrice = ((item.getMemberPrice().multiply(new BigDecimal(100)).divide(new BigDecimal(100))
											.multiply(new BigDecimal(item.getTotalGoodsCount())))
											.multiply(receivedAmount))
											.divide(memberOrderAmount,2,BigDecimal.ROUND_HALF_UP);
								}
							} else {
								salePrice = ((item.getMemberPrice().multiply(new BigDecimal(100)).divide(new BigDecimal(100))
										.multiply(new BigDecimal(item.getTotalGoodsCount())))
										.multiply(receivedAmount))
										.divide(memberOrderAmount,2,BigDecimal.ROUND_HALF_UP);
							}
							/************* 次卡买门票计算end  **************/
						}else if (item.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
							salePrice = ((item.getMemberPrice().multiply(new BigDecimal(100)).divide(new BigDecimal(100))
									.multiply(new BigDecimal(item.getTotalGoodsCount())))
									.multiply(receivedAmount))
									.divide(memberOrderAmount,2,BigDecimal.ROUND_HALF_UP);
						}
					}
				} else {
					//散客
					salePrice = ((item.getOriginPrice().multiply(new BigDecimal(item.getTotalGoodsCount())))
							.multiply(receivedAmount))
							.divide(orderAmount,2,BigDecimal.ROUND_HALF_UP);
				}
			}

			item.setSalePrice(salePrice);

			if (index == tbBizPlaceOrderItems.size()){
				item.setSalePrice(receivedAmount.subtract(lastBeforeAmount));
			}else{
				lastBeforeAmount = lastBeforeAmount.add(item.getSalePrice());
			}

			/*if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getMemberCardId())) {
				//次卡不需要实付金额
				if (tbBizPlaceMemberCard.getCardType() != PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.intValue()){
					if (index == tbBizPlaceOrderItems.size()){
						item.setSalePrice(receivedAmount.subtract(lastBeforeAmount));
					}else{
						lastBeforeAmount = lastBeforeAmount.add(item.getSalePrice());
					}
				}
			}*/

			list.add(item);

		}
		return list;
	}

	/**
	 * 计算订单手动调价(填充订单缺失信息)  [填充手动调价]
	 * @param map
	 * @return
	 */
	private Map calcOrderInfo(Map map){
		TbBizPlaceOrder order = new TbBizPlaceOrder();
		List<TbBizPlaceOrderItem> allItems = new ArrayList<>();
		List<TbBizPlacePayItem> pays = new ArrayList<>();
		List<TbBizPlaceOrderDiscountItem> allDiscountItems = new ArrayList<>();

		order = (TbBizPlaceOrder)  MapUtils.getObject(map, "order");
		allItems = (List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items");
		pays = (List<TbBizPlacePayItem>) MapUtils.getObject(map, "pays");
		allDiscountItems = (List<TbBizPlaceOrderDiscountItem>) MapUtils.getObject(map, "discount");

		//订单金额
		BigDecimal orderDebit = new BigDecimal(0);
		if (!CollectionUtils.isEmpty(allItems)){
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : allItems){
				orderDebit = orderDebit.add(tbBizPlaceOrderItem.getOriginPrice().multiply(new BigDecimal(tbBizPlaceOrderItem.getTotalGoodsCount())));
			}
		}
		order.setDebit(orderDebit);
		//// TODO: 17/4/13 填充订单金额,调价、 优惠明细调价项
		if (org.springframework.util.StringUtils.isEmpty(order)){
			return map;
		}
		if (CollectionUtils.isEmpty(pays)){
			return map;
		}

		/**订单改价  改价=售卖价-会员优惠-实付金额**/
		//订单总改价
		BigDecimal handAdjustAmount = new BigDecimal(0);
		if (!CollectionUtils.isEmpty(allItems)){
			List<TbBizPlaceOrderDiscountItem> discountItemList = new ArrayList<>();
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : allItems){
				//赠送商品不参与优惠
				if (tbBizPlaceOrderItem.getSalePrice().equals(BigDecimal.ZERO) && tbBizPlaceOrderItem.getIsGive().equals(PlaceConstants.YES)){
					continue;
				}
				//每个明细的会员优惠
				BigDecimal itemDiscountAmount = new BigDecimal(0);
				if (!CollectionUtils.isEmpty(allDiscountItems)){
					for (TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem : allDiscountItems){
						if (tbBizPlaceOrderDiscountItem.getPlaceOrderId().equals(tbBizPlaceOrderItem.getPlaceOrderId())
								&& tbBizPlaceOrderDiscountItem.getOrderItemUuid().equals(tbBizPlaceOrderItem.getItemUuid())){
							itemDiscountAmount = itemDiscountAmount.add(tbBizPlaceOrderDiscountItem.getDiscountMember() == null ? BigDecimal.ZERO : tbBizPlaceOrderDiscountItem.getDiscountMember())
									.add(tbBizPlaceOrderDiscountItem.getDiscountDiscountMember() == null ? BigDecimal.ZERO : tbBizPlaceOrderDiscountItem.getDiscountDiscountMember())
									.add(tbBizPlaceOrderDiscountItem.getDiscountNumberMember() == null ? BigDecimal.ZERO : tbBizPlaceOrderDiscountItem.getDiscountNumberMember());
							//明细改价优惠   明细原价-会员优惠-实付 = 调价
							BigDecimal itemAdjust =
									tbBizPlaceOrderItem.getOriginPrice().multiply(new BigDecimal(tbBizPlaceOrderItem.getTotalGoodsCount())).subtract(itemDiscountAmount).subtract(tbBizPlaceOrderItem.getSalePrice());
							tbBizPlaceOrderDiscountItem.setDiscountAdjust(itemAdjust);

							handAdjustAmount = handAdjustAmount.add(itemAdjust);
							discountItemList.add(tbBizPlaceOrderDiscountItem);
						}
					}
				} else {
					BigDecimal itemAdjust =
							tbBizPlaceOrderItem.getOriginPrice().multiply(new BigDecimal(tbBizPlaceOrderItem.getTotalGoodsCount())).subtract(BigDecimal.ZERO).subtract(tbBizPlaceOrderItem.getSalePrice())
					;
					if (itemAdjust.compareTo(BigDecimal.ZERO) != 0){
						TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem = new TbBizPlaceOrderDiscountItem();
						tbBizPlaceOrderDiscountItem.setOrderItemUuid(tbBizPlaceOrderItem.getItemUuid());
						tbBizPlaceOrderDiscountItem.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
						tbBizPlaceOrderDiscountItem.setStatus(tbBizPlaceOrderItem.getStatus());
						tbBizPlaceOrderDiscountItem.setDiscountAdjust(itemAdjust);

						handAdjustAmount = handAdjustAmount.add(itemAdjust);
						discountItemList.add(tbBizPlaceOrderDiscountItem);
					}
				}
			}
			map.put("discount",discountItemList);
		}
		order.setHandAdjustAmount(BigDecimal.ZERO.subtract(handAdjustAmount));

		return map;
	}

	/**
	 * 生成会员优惠明细
	 * @param tbBizPlaceOrderItemList
	 * @param tbBizPlaceMemberCard
	 * @return
	 */
	private List<TbBizPlaceOrderDiscountItem> createDiscountItemByMemberCard(List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList,
	                                                                         TbBizPlaceMemberCard tbBizPlaceMemberCard){
		BigDecimal discount = new BigDecimal(100);
		List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList = new ArrayList<>();

		if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard)){
			if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard.getDiscount())){
				discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
			}
		}

		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
			//赠送商品不参与优惠
			if (tbBizPlaceOrderItem.getSalePrice().equals(BigDecimal.ZERO) && tbBizPlaceOrderItem.getIsGive().equals(PlaceConstants.YES)){
				continue;
			}
			TbBizPlaceOrderDiscountItem tbBizPlaceOrderDiscountItem = new TbBizPlaceOrderDiscountItem();
			tbBizPlaceOrderDiscountItem.setOrderItemUuid(tbBizPlaceOrderItem.getItemUuid());
			tbBizPlaceOrderDiscountItem.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
			tbBizPlaceOrderDiscountItem.setStatus(PlaceConstants.ORDER_PREPAY_STATUS.intValue());
			//会员价优惠  (商品会员价-商品散客价)*商品个数
			if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard)){
				tbBizPlaceOrderDiscountItem.setDiscountMember((tbBizPlaceOrderItem.getOriginPrice()).
						subtract(tbBizPlaceOrderItem.getMemberPrice()).multiply(new BigDecimal(tbBizPlaceOrderItem.getTotalGoodsCount())));//会员价优惠
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())
						|| PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())) {
					//门票，小商品不参与打折
					if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
							|| tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
							|| tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)) {
						//会员折扣优惠 (会员价-会员价*折扣)*商品个数
						tbBizPlaceOrderDiscountItem.setDiscountDiscountMember((tbBizPlaceOrderItem.getMemberPrice().subtract(tbBizPlaceOrderItem.getMemberPrice().multiply(discount).divide(new BigDecimal(100)))).
										multiply(new BigDecimal(tbBizPlaceOrderItem.getTotalGoodsCount())));//会员折扣优惠
					} else {
						tbBizPlaceOrderDiscountItem.setDiscountDiscountMember(BigDecimal.ZERO);
					}
				}
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())) {
					//次卡买门票需要保存次卡优惠
					if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)) {
						//次卡门票优惠 (门票会员价)*商品个数 - salePrice
						tbBizPlaceOrderDiscountItem.setDiscountNumberMember(tbBizPlaceOrderItem.getMemberPrice().subtract(tbBizPlaceOrderItem.getSalePrice()
								.multiply(new BigDecimal(tbBizPlaceOrderItem.getTotalGoodsCount()))));//次卡优惠
					}
				}
				tbBizPlaceOrderDiscountItem.setMemberCardNo(tbBizPlaceMemberCard.getInnerCardNo());//会员卡号
			}

			tbBizPlaceOrderDiscountItem.setDiscountAdjust(null);//调价 外层需要填充

			tbBizPlaceOrderDiscountItemList.add(tbBizPlaceOrderDiscountItem);
		}

		return tbBizPlaceOrderDiscountItemList;
	}

	/**
	 * 校验购物车会员信息
	 * @param reqShoppingCart
	 * @return
     */
	private APIResponse<?> checkMemberCardShoppingCartInfo(ReqShoppingCart reqShoppingCart,Map map){
		TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqShoppingCart.getMemberCardId());
		List<TbBizPlaceOrderItem> allItems = new ArrayList<>();
		allItems = (List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items");
		if (CollectionUtils.isEmpty(allItems)){
			return APIResponse.returnFail("请添加商品到购物车");
		}
		//按场地，门票，商品分组
		List<TbBizPlaceOrderItem> billingOrderItems = new ArrayList<>();
		List<TbBizPlaceOrderItem> ticketOrderItems = new ArrayList<>();
		List<TbBizPlaceOrderItem> goodsOrderItems = new ArrayList<>();
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : allItems){
			//开单
			if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
				billingOrderItems.add(tbBizPlaceOrderItem);
			}
			//门票
			if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
				ticketOrderItems.add(tbBizPlaceOrderItem);
			}
			//商品
			if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
				goodsOrderItems.add(tbBizPlaceOrderItem);
			}
		}
		//次卡是否可用于本次消费
		if(tbBizPlaceMemberCard.getCardType().equals(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER)){
			if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(billingOrderItems)||com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(goodsOrderItems)){
				return APIResponse.returnFail("该次卡仅能用于购买门票");
			}else if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(ticketOrderItems)){
				int cardTypeId = tbBizPlaceMemberCard.getCardTypeId();
				TbBizPlaceMemberCardTypeTicket tbBizPlaceMemberCardTypeTicket = new TbBizPlaceMemberCardTypeTicket();
				TbBizPlaceMemberCardTypeTicketExample example = new TbBizPlaceMemberCardTypeTicketExample();
				TbBizPlaceMemberCardTypeTicketExample.Criteria criteria = example.createCriteria();
				criteria.andCardTypeIdEqualTo(cardTypeId);
				List<TbBizPlaceMemberCardTypeTicket> list = tbBizPlaceMemberCardTypeTicketMapper.selectByExample(example);
				if(!CollectionUtils.isEmpty(list)){
					tbBizPlaceMemberCardTypeTicket = list.get(0);
					int ticketId = tbBizPlaceMemberCardTypeTicket.getTicketId();
					TbPlaceTicketSalePlan tbPlaceTicketSalePlan = tbPlaceTicketSalePlanMapper.selectByPrimaryKey(ticketId);
					String ticketName = tbPlaceTicketSalePlan.getTicketName();
					for (TbBizPlaceOrderItem item : ticketOrderItems){
						if(item.getUnitSalePlanId()!=ticketId){
							return APIResponse.returnFail("该次卡仅能用于购买门票："+ticketName);
						}
					}
				}
			}
		}

		if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(billingOrderItems)||com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(ticketOrderItems)){
			//运动项目是否可用
			if(tbBizPlaceMemberCard.getCategoryIds()!=null){
				String categoryIds = tbBizPlaceMemberCard.getCategoryIds();
				List categoryList = JSON.parseArray(categoryIds);
				String categoryStr = "";
				for (int i=0;i<categoryList.size();i++){
					categoryStr = categoryStr+iBaseService.getCommonDataCache("cagetory" + categoryList.get(i));
				}
				List<TbBizPlaceOrderItem> list = new ArrayList<>();
				list.addAll(billingOrderItems);
				list.addAll(ticketOrderItems);
				for (TbBizPlaceOrderItem tbBizPlaceOrderItem : list){
					if (categoryIds.indexOf(tbBizPlaceOrderItem.getCategoryId().toString()) == -1){//不存在运动类型返回-1
						return APIResponse.returnFail("该会员卡仅能用于"+JSON.toJSON(categoryStr).toString()+"项目消费");
					}
				}
			}

		}
		//是否可购买门票
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(ticketOrderItems)){
			if(tbBizPlaceMemberCard.getIsSupportTickets().equals(PlaceConstants.NO)){
				return APIResponse.returnFail("该会员卡不可用于购买门票");
			}
		}
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(billingOrderItems)||com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(ticketOrderItems)) {
			//时段是否可用
			List<TbBizPlaceOrderItem> list = new ArrayList<>();
			list.addAll(billingOrderItems);
			list.addAll(ticketOrderItems);
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : list) {
				boolean flag1 = DateUtils.dateCompare(tbBizPlaceOrderItem.getStartTime(), tbBizPlaceMemberCard.getAvailableStartTime(), true);//销售计划开始时间>=会员卡优惠开始时间返回true
				boolean flag2 = DateUtils.dateCompare(tbBizPlaceMemberCard.getAvailableEndTime(), tbBizPlaceOrderItem.getEndTime(), true);//会员卡优惠结束时间>=销售计划结束时间返回true
				if (!(flag1 && flag2)) {
					return APIResponse.returnFail("该会员卡仅能用于" +
							DateTimeUtils.convertDate2String("HH:mm", tbBizPlaceMemberCard.getAvailableStartTime()) +
							"-" + DateTimeUtils.convertDate2String("HH:mm", tbBizPlaceMemberCard.getAvailableEndTime()) +
							"时间段");
				}
			}
		}
		BigDecimal initAmount = org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusAmount())?BigDecimal.ZERO:tbBizPlaceMemberCard.getSurplusAmount();
		BigDecimal initGiveAmount = org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusGiveAmount())?BigDecimal.ZERO:tbBizPlaceMemberCard.getSurplusGiveAmount();
		BigDecimal receiveAmount = new BigDecimal(0);
		if (!org.springframework.util.StringUtils.isEmpty(reqShoppingCart.getReceivedAmount())){
			receiveAmount = receiveAmount.add(new BigDecimal(reqShoppingCart.getReceivedAmount()));
		}
		//赠送金额是否可用于购买商品
		if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(goodsOrderItems)){
			BigDecimal goodPrice = BigDecimal.ZERO;
			for (TbBizPlaceOrderItem item : goodsOrderItems){
				goodPrice = goodPrice.add(item.getMemberPrice().multiply(new BigDecimal(item.getTotalGoodsCount())));
			}
			//当购物车包含商品，且商品金额大于会员卡本金，但会员卡总余额（本金+赠送金额）大于等于应付金额，需判断该会员卡赠送金额是否可用于购买商品

			/*if(goodPrice.compareTo(initAmount)>0&&initAmount.add(initGiveAmount).compareTo(receiveAmount)>0){
				if(tbBizPlaceMemberCard.getGiveAmountIsUse()!=null&&tbBizPlaceMemberCard.getGiveAmountIsUse()==1) {
					return APIResponse.returnFail("该会员卡赠送金额不足，不能用于购买商品");
				}else {
					return APIResponse.returnFail("该会员卡赠送不能用于购买商品");
				}
			}*/
			//商品金额大于本金
			if (goodPrice.compareTo(initAmount) > 0){
				//商品金额大于 本金+赠送
				if(tbBizPlaceMemberCard.getGiveAmountIsUse()!=null&&tbBizPlaceMemberCard.getGiveAmountIsUse()==1) {
					if (goodPrice.compareTo(initAmount.add(initGiveAmount)) > 0){
						return APIResponse.returnFail("该会员卡赠送金额不足，不能用于购买商品");
					}
				}else {
					return APIResponse.returnFail("该会员卡赠送金额不能用于购买商品");
				}
			}
		}
		return APIResponse.returnSuccess(tbBizPlaceMemberCard);
	}

	/**
	 * 购物车生成订单支付信息
	 * @param adminPayType
	 * @param tbBizPlaceOrderItemList
	 * @param orderId
     * @return
     */

	private APIResponse<?> shoppingCart2PayItem(Integer adminPayType,List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList, String orderId){
		if (org.springframework.util.StringUtils.isEmpty(adminPayType)){
			return APIResponse.returnFail("支付方式必传");
		}
		List<TbBizPlacePayItem> tbBizPlacePayItemList = new ArrayList<>();
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
			TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();

			tbBizPlacePayItem.setPlaceOrderId(orderId);
			tbBizPlacePayItem.setOrderItemUuid(tbBizPlaceOrderItem.getItemUuid());
			if (org.springframework.util.StringUtils.isEmpty(tbBizPlaceOrderItem.getSalePrice())){
				return APIResponse.returnFail("订单明细实付金额异常");
			}else {
				tbBizPlacePayItem.setAmount(tbBizPlaceOrderItem.getSalePrice());
			}
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
			if (PlaceConstants.YES.equals(tbBizPlaceOrderItem.getIsGive())){
				tbBizPlacePayItem.setPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_GIVE));
				tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_GIVE)).getUnifiedId());
			}else {
				tbBizPlacePayItem.setPayType(adminPayType);
				tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			}

			tbBizPlacePayItemList.add(tbBizPlacePayItem);
		}
		return APIResponse.returnSuccess(tbBizPlacePayItemList);
	}

	/**
	 * 购物车生成订单信息
	 * @param reqShoppingCart
	 * @param orderId
     * @return
     */
	private TbBizPlaceOrder shoppingCart2Order(ReqShoppingCart reqShoppingCart,String orderId){
		TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
		tbBizPlaceOrder.setPlaceOrderId(orderId);
		tbBizPlaceOrder.setPlaceId(reqShoppingCart.getPlaceId());
		tbBizPlaceOrder.setDate(new Date());
		tbBizPlaceOrder.setOrderTime(new Date());
		tbBizPlaceOrder.setMobile(reqShoppingCart.getContactInformation());
		tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
		tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_SHOPPING_CART);
		tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
		tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
		tbBizPlaceOrder.setDescrible(reqShoppingCart.getMemo());
		//场馆运营模式
		TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqShoppingCart.getPlaceId());
		tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());
		tbBizPlaceOrder.setCreateUid(reqShoppingCart.getCreateUid());
		tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
		tbBizPlaceOrder.setExpression(reqShoppingCart.getExpression());

		//退款时需要修改以下两项
		tbBizPlaceOrder.setCredit(null);
		tbBizPlaceOrder.setRefundTime(null);
		//支付中心订单号
		tbBizPlaceOrder.setOrderNo(null);
		tbBizPlaceOrder.setParentId(null);
		tbBizPlaceOrder.setEnableRefund(null);
		tbBizPlaceOrder.setUpdateUid(null);

		//订单修改日期
		tbBizPlaceOrder.setOrderStatusChangeDate(null);

		//默认非会员（需要外层修改）判断会员身份
		tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
		tbBizPlaceOrder.setInnerCardNo(null);

		//统一未付款状态（需要外层修改）
		tbBizPlaceOrder.setEndTime(null);
		tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
		tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);

		//（需要外层修改）
		tbBizPlaceOrder.setDebit(null);
		tbBizPlaceOrder.setHandAdjustAmount(null);

		tbBizPlaceOrder.setCategoryId(0);


		//=====
		//调用支付中心需要修改回调支付时间
		tbBizPlaceOrder.setPaymentTime(null);
		//下单用户
		tbBizPlaceOrder.setUid(null);
		tbBizPlaceOrder.setCustomerName(reqShoppingCart.getCreateUserName());

		return tbBizPlaceOrder;
	}
	/**
	 * 购物车生成订单明细
	 * @param reqShoppingCart
	 * @return
	 */
	private APIResponse<?> shoppingCart2OrderItem(ReqShoppingCart reqShoppingCart,String orderId,final boolean checkBilling){

		Map orderItemsReqPlaceOrderListVoMap = new HashMap();

		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = new ArrayList<TbBizPlaceOrderItem>();

		//订场业务
		if (reqShoppingCart.getReqBillingInfo() != null){
			List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = null;
			try{
				//校验购物车中的场地信息
				APIResponse response = checkGoodCartForBilling(reqShoppingCart,checkBilling);
				if (!response.isRet()){
					throw new BizException(response.getErrmsg());
				}
				Map reqPlaceOrderListVoTbBizPlaceUnitSalePlansMap = (Map)response.getData();
				tbBizPlaceUnitSalePlans = (List<TbBizPlaceUnitSalePlan>)MapUtils.getObject(reqPlaceOrderListVoTbBizPlaceUnitSalePlansMap,"tbBizPlaceUnitSalePlans");
				ReqPlaceOrderListVo reqPlaceOrderListVo = (ReqPlaceOrderListVo)MapUtils.getObject(reqPlaceOrderListVoTbBizPlaceUnitSalePlansMap,"reqPlaceOrderListVo");

				orderItemsReqPlaceOrderListVoMap.put("reqPlaceOrderListVo",reqPlaceOrderListVo);

				if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
					return APIResponse.returnFail("销售计划为空");
				}
			}catch (Exception e){
				return APIResponse.returnFail(e.getMessage());
			}

			List<TbBizPlaceOrderItem> billingItemList =
					this.tbBizPlaceUnitSalePlan2OrderItem(tbBizPlaceUnitSalePlans,orderId,PlaceConstants.ORDER_PREPAY_STATUS.intValue(),reqShoppingCart.getCreateUid(),null);
			tbBizPlaceOrderItemList.addAll(billingItemList);
		}
		//门票业务
		if (reqShoppingCart.getReqTicketPay() != null){
			try{
				//校验购物车中的门票信息
				APIResponse response = checkGoodCartForTicket(reqShoppingCart);
				if (!response.isRet()){
					return response;
				}
			}catch (Exception e){
				logger.error(e.fillInStackTrace().toString());
				return APIResponse.returnFail("校验购物车门票信息异常");
			}
			List<TbBizPlaceOrderItem> ticketItemList =
					this.tbTicketSalePlan2OrderItem(reqShoppingCart.getReqTicketPay().getTicketSaleList(),orderId,PlaceConstants.ORDER_PREPAY_STATUS.intValue(),reqShoppingCart.getCreateUid(),null);
			tbBizPlaceOrderItemList.addAll(ticketItemList);
		}
		//小商品业务
		if (reqShoppingCart.getReqPlaceGoodsVo() != null){
			try{
				//校验购物车中的小商品信息
				APIResponse response = checkGoodCartForGoods(reqShoppingCart.getReqPlaceGoodsVo());
				if (!response.isRet()){
					return response;
				}
			}catch (Exception e){
				logger.error(e.fillInStackTrace().toString());
				return APIResponse.returnFail("校验购物车商品信息异常");
			}
			List<TbBizPlaceOrderItem> goodsItemList =
					this.tbGoods2OrderItem(reqShoppingCart.getReqPlaceGoodsVo().getGoodsList(),orderId,PlaceConstants.ORDER_PREPAY_STATUS.intValue(),reqShoppingCart.getCreateUid(),null);
			tbBizPlaceOrderItemList.addAll(goodsItemList);
		}

		orderItemsReqPlaceOrderListVoMap.put("tbBizPlaceOrderItemList",tbBizPlaceOrderItemList);
		return APIResponse.returnSuccess(orderItemsReqPlaceOrderListVoMap);
	}

	
	private BigDecimal getReceivedAmount(String placeOrderId) {
		BigDecimal mount = new BigDecimal(0);
		
		TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
		tbBizPlaceOrderItemExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
		 
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemLsit = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemLsit)) {
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemLsit) {
				mount.add(tbBizPlaceOrderItem.getSalePrice());
			}
		}
		return mount;
	}
	
	@Override
	public void checkBlockOrder(TbBizPlaceOrder placeOrder, Byte orderStatus ,BigDecimal receivedAmount) {
		
           TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
           Criteria criteriat = tbBizPlaceOrderExample.createCriteria();
           criteriat.andParentIdEqualTo(placeOrder.getParentId());
           
           TbBizPlacePrivateOrderExample tbBizPlacePrivateOrderExample = new TbBizPlacePrivateOrderExample();
    	   tbBizPlacePrivateOrderExample.createCriteria().andIdEqualTo(placeOrder.getParentId());
    	   
    	   List<TbBizPlacePrivateOrder> bizPlacePrivateOrderList = tbBizPlacePrivateOrderMapper.selectByExample(tbBizPlacePrivateOrderExample);
    	   TbBizPlacePrivateOrder tbBizPlacePrivateOrder = bizPlacePrivateOrderList.get(0);
           
           String opname = "";
           BigDecimal mount = new BigDecimal(0);
           Byte paytype = null; 
           byte state = PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO;
           
           boolean cancelFlag = false;
           
           if (PlaceConstants.ORDER_PAYED_STATUS.equals(orderStatus)) {//已付款
        	   //是否子订单全部已付款  是否手动调价？
        	   criteriat.andOrderStatusNotIn(Arrays.asList(orderStatus,PlaceConstants.ORDER_CLOSE_STATUS,
        			   PlaceConstants.ORDER_COMPLETE_PAY_STATUS));
    		   opname = "支付";
        	   if (receivedAmount == null) {
        		   receivedAmount  = getReceivedAmount(placeOrder.getPlaceOrderId());
			   }
        	   mount  = mount.add(receivedAmount);
        	   paytype = PlaceConstants.PAY_STATUS;
        	   state = PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES;
        	   
			} else if (PlaceConstants.ORDER_REFUND_STATUS.equals(orderStatus)) {//已退款
				//是否子订单全部已退款  是否手动调价？
				criteriat.andOrderStatusNotIn(Arrays.asList(orderStatus,PlaceConstants.ORDER_CLOSE_STATUS,
	        			   PlaceConstants.ORDER_COMPLETE_PAY_STATUS));
				
				opname = "退款";
				mount  = mount.subtract(receivedAmount);
				paytype = PlaceConstants.REFUNDING_STATUS;
				
				
			} else if (PlaceConstants.ORDER_CLOSE_STATUS.equals(orderStatus)) {//已取消预定
				//1.全部取消预定  2.剩余部分已付款  3.剩余部分已退款 
				criteriat.andOrderStatusNotEqualTo(orderStatus);
				if (tbBizPlaceOrderMapper.countByExample(tbBizPlaceOrderExample) < 1) {
					opname = "取消";
					paytype = PlaceConstants.NOT_PAY_STATUS;
					cancelFlag = true;
					tbBizPlacePrivateOrder.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
				} else {
					  criteriat.andOrderStatusNotIn(Arrays.asList(PlaceConstants.ORDER_PAYED_STATUS,PlaceConstants.ORDER_CLOSE_STATUS,
		        			   PlaceConstants.ORDER_COMPLETE_PAY_STATUS));
					  if (tbBizPlaceOrderMapper.countByExample(tbBizPlaceOrderExample) < 1) {
						  opname = "支付";
						  paytype = PlaceConstants.PAY_STATUS;
			        	  state = PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES;
			        	  tbBizPlacePrivateOrder.setPaymentTime(new Date());
			        	  cancelFlag = true;
			        	  tbBizPlacePrivateOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
					  } else {
						  criteriat.andOrderStatusNotIn(Arrays.asList(PlaceConstants.ORDER_REFUND_STATUS,PlaceConstants.ORDER_CLOSE_STATUS,
			        			   PlaceConstants.ORDER_COMPLETE_PAY_STATUS));
						  if (tbBizPlaceOrderMapper.countByExample(tbBizPlaceOrderExample) < 1) {
								opname = "退款";
								paytype = PlaceConstants.REFUNDING_STATUS;
								tbBizPlacePrivateOrder.setRefundTime(new Date());
								cancelFlag = true;
								tbBizPlacePrivateOrder.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
								 state = PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO;
						  }
					  }
				}
			}
           boolean finishFlag = cancelFlag || tbBizPlaceOrderMapper.countByExample(tbBizPlaceOrderExample) < 1;
           if (finishFlag) {
        	    tbBizPlacePrivateOrder.setEndTime(new Date());
        		tbBizPlacePrivateOrder.setPayStatus(paytype);
        		if (!cancelFlag) {
        			tbBizPlacePrivateOrder.setOrderStatus(orderStatus);
        			tbBizPlacePrivateOrder.setDebit(tbBizPlacePrivateOrder.getDebit().add(mount));
				}
        		if (PlaceConstants.ORDER_PAYED_STATUS.equals(orderStatus)) {//已付款
					tbBizPlacePrivateOrder.setPaymentTime(new Date());
				} else if (PlaceConstants.ORDER_REFUND_STATUS.equals(orderStatus)) {//已退款
					tbBizPlacePrivateOrder.setRefundTime(new Date());//???
					state = PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO;
				}
        		tbBizPlacePrivateOrderMapper.updateByPrimaryKeySelective(tbBizPlacePrivateOrder);
		   }
	}


	/**
	 * 购物车取消预订
	 * @param reqPlaceOrderId
	 * @return
	 */
	public APIResponse<?> placeCancelShoppingCard(String reqPlaceOrderId) {
		if (org.springframework.util.StringUtils.isEmpty(reqPlaceOrderId)) {
			return APIResponse.returnFail("取消预订失败");
		}
		try {
			cancelShoppingCard(reqPlaceOrderId);
		} catch (Exception e) {
			return APIResponse.returnFail(e.getMessage());
		}
		return APIResponse.returnSuccess();
	}

	/**
	 * 购物车退款
	 * @param placeOrderId
	 * @return
	 * @throws Exception
     */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public APIResponse placeRefundShoppingCard(String placeOrderId,Integer operateUid) throws Exception {
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
		tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		if (CollectionUtils.isEmpty(tbBizPlaceOrderList)){
			return APIResponse.returnFail("not fund order");
		}
		TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrderList.get(0);
		if (tbBizPlaceOrder.getPayStatus().intValue() != PlaceConstants.PAY_STATUS.intValue()
				&& tbBizPlaceOrder.getOrderStatus().intValue() != PlaceConstants.ORDER_PAYED_STATUS){
			return APIResponse.returnFail("not pay order");
		}
		if (tbBizPlaceOrder.getOrderStatus().intValue() != PlaceConstants.ORDER_PAYED_STATUS){
			return  APIResponse.returnFail("order status not support refund");
		}
		if (!tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
			return APIResponse.returnFail("only support refund shopping cart order");
		}
		TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
		TbBizPlaceOrderItemExample.Criteria tbBizPlaceOrderItemCriteria = tbBizPlaceOrderItemExample.createCriteria();
		tbBizPlaceOrderItemCriteria.andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);

		TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
		if (tbBizPlaceOrder.getIsMember().equals(PlaceConstants.YES)){
			TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
			TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
			tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(tbBizPlaceOrder.getInnerCardNo());
			tbBizPlaceMemberCardExample.setOrderByClause(" id for update ");
			List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
			tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
		}

		BigDecimal refundPrice = new BigDecimal(0);
		if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
				//次卡支付不能算金额
				if (tbBizPlaceMemberCard !=null && tbBizPlaceMemberCard.getCardType().equals(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER)){
					continue;
				}
				refundPrice = refundPrice.add(tbBizPlaceOrderItem.getSalePrice());
			}
		}

		//线下退款
		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
		BeanUtils.copyProperties(tbBizPlaceOrder, newTbBizPlaceOrder);
		//修改订单状态
		newTbBizPlaceOrder.setId(tbBizPlaceOrder.getId());
		newTbBizPlaceOrder.setPlaceOrderId(placeOrderId);
		newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
		newTbBizPlaceOrder.setCredit(refundPrice);//退款金额
		newTbBizPlaceOrder.setRefundTime(new Date());//退款时间

		TbBizPlaceOrderItem newTbBizPlaceOrderItem = new TbBizPlaceOrderItem();
		TbBizPlacePayItem newTbBizPlacePayItem = new TbBizPlacePayItem();
		TbBizPlaceOrderDiscountItem newTbBizPlaceOrderDiscountItem = new TbBizPlaceOrderDiscountItem();

		TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
		TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
		tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);

		TbBizPlaceOrderDiscountItemExample tbBizPlaceOrderDiscountItemExample = new TbBizPlaceOrderDiscountItemExample();
		TbBizPlaceOrderDiscountItemExample.Criteria tbBizPlaceOrderDiscountItemCriteria = tbBizPlaceOrderDiscountItemExample.createCriteria();
		tbBizPlaceOrderDiscountItemCriteria.andPlaceOrderIdEqualTo(placeOrderId);

		List<String> payTypeList = new ArrayList<>();
		for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList){
			payTypeList.add(tbBizPlacePayItem.getPayType().toString());
		}

		if (payTypeList.contains(PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN)
				|| payTypeList.contains(PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN)){
			//扫码退款  订单状态 = 退款中
			newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);

			newTbBizPlaceOrderItem.setStatus(PlaceConstants.ORDER_REFUNDING_STATUS.intValue());

			newTbBizPlaceOrderDiscountItem.setStatus(PlaceConstants.ORDER_REFUNDING_STATUS.intValue());
		}else{
			newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
			newTbBizPlaceOrder.setPayStatus(PlaceConstants.REFUNDING_STATUS);

			newTbBizPlaceOrderItem.setStatus(PlaceConstants.ORDER_REFUND_STATUS.intValue());
			newTbBizPlaceOrderItem.setSurplusGoodsCount(0);//商品剩余个数置0

			newTbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);

			newTbBizPlaceOrderDiscountItem.setStatus(PlaceConstants.ORDER_REFUND_STATUS.intValue());
		}

		//减库存相关操作
		newTbBizPlaceOrder = this.shoppingCartOrderRefund(tbBizPlaceOrderItemList,newTbBizPlaceOrder,tbBizPlacePayItemList);

		try {
			//退款日志
			TbBusinessLog log = new TbBusinessLog();
			log.setEntityId(tbBizPlaceOrder.getId());
			log.setEntityType(PlaceConstants.LOG_TYPE_PLACE_ORDER);
			log.setUid(operateUid);
			log.setLogName("商家端退款");
			log.setLogInfo("订单号：[" + tbBizPlaceOrder.getPlaceOrderId() + "]" + " 退款人：[" + tbBizPlaceOrder.getCustomerName() + "],订单金额：[" + tbBizPlaceOrder.getDebit() + "]" + "电话：[" + tbBizPlaceOrder.getMobile() + "]");
			tbBusinessLogService.insertLogInfo(log);
		} catch (Exception e) {
			throw new Exception("退款日志生成失败.");
		}
		TbBizPlaceOrderExample updateOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria updateOrderCriteria = updateOrderExample.createCriteria();
		updateOrderCriteria.andOrderStatusLessThanOrEqualTo(PlaceConstants.ORDER_REFUNDING_STATUS);
		updateOrderCriteria.andPlaceOrderIdEqualTo(newTbBizPlaceOrder.getPlaceOrderId());
		TbBizPlaceOrder updateTbBizPlaceOrder = new TbBizPlaceOrder();
		BeanUtils.copyProperties(newTbBizPlaceOrder,updateTbBizPlaceOrder);
		updateTbBizPlaceOrder.setId(null);//设置为空，否则报Duplicate entry 'xxx' for key 'PRIMARY'
		if (this.tbBizPlaceOrderMapper.updateByExampleSelective(newTbBizPlaceOrder,updateOrderExample) == 0) {
			throw new Exception("该订单不能重复退款.");
		}
		//退订单明细
		tbBizPlaceOrderItemMapper.updateByExampleSelective(newTbBizPlaceOrderItem,tbBizPlaceOrderItemExample);

		//退支付明细
		if (!org.springframework.util.StringUtils.isEmpty(newTbBizPlacePayItem.getAmountType())){
			tbBizPlacePayItemMapper.updateByExampleSelective(newTbBizPlacePayItem,tbBizPlacePayItemExample);
		}
		//退优惠明细
		tbBizPlaceOrderDiscountItemMapper.updateByExampleSelective(newTbBizPlaceOrderDiscountItem,tbBizPlaceOrderDiscountItemExample);

		//添加会员支付后退款(退到会员卡)
		boolean numCardRefund = false;//次卡退款标记
		int refundNum = 0;//次卡退款次数
		//获取会员卡
		TbBizPlaceMemberOpHistoryExample example = new TbBizPlaceMemberOpHistoryExample();
		TbBizPlaceMemberOpHistoryExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(placeOrderId);
		example.setOrderByClause(" id for update ");
		List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)) {
			String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
			if (!org.springframework.util.StringUtils.isEmpty(innerCardNo)) {
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())){
					//次卡退款
					tbBizPlaceMemberCard.setSurplusNumbers(tbBizPlaceMemberCard.getSurplusNumbers()+tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount());
					numCardRefund = true;
					refundNum = tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount();
				} else {
					//储值，折扣卡，储值折扣卡退款
					tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterAmount())));
					tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterGiveAmount())));
				}
				int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
				if (flag1 == 1) {
					TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
					//退款生成订单号
					String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, operateUid);
					tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
					tbBizPlaceMemberOpHistory.setRefundNo(tbBizPlaceMemberOpHistoryList.get(0).getOrderNo());
					tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
					tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
					tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
					tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
					tbBizPlaceMemberOpHistory.setAmount(tbBizPlaceMemberOpHistoryList.get(0).getAmount());
					tbBizPlaceMemberOpHistory.setCreateTime(new Date());
					tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
					tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
					if (tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName().indexOf("抵扣") != -1){
						tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName().replace("抵扣","退款"));
					}else{
						tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName() + "退款");
					}
					tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
					tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
					tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
					tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
					tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList.get(0).getMemo());
					tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
					tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
					tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
					tbBizPlaceMemberOpHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterAmount())));
					tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterGiveAmount())));
					tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
					tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
					tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
					tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());
					tbBizPlaceMemberOpHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers()-(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeNumbers()-tbBizPlaceMemberOpHistoryList.get(0).getOpAfterNumbers()));
					tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
					tbBizPlaceMemberOpHistory.setOpCardCount(tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount());
					tbBizPlaceMemberOpHistory.setPlatform(5);
					int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
					if (flag2 != 1) {
						throw new Exception("生成退款流水失败.");
					}
				} else {
					throw new Exception("修改会员卡失败.");
				}
			} else {
				throw new Exception("会员卡异常.");
			}
		}else {
			logger.debug("非会员退款.");
		}
		/*if (numCardRefund && refundNum > 0){
			//插入退款流水
			ReqOrderHistory reqOrderHistory = placeOrderUtilService.memberTicket2ReqOrderHistory(newTbBizPlaceOrder,refundNum,(byte)1,(byte)0);
			placeOrderUtilService.insertOrderHistory(reqOrderHistory);
		}else {
			if (PlaceConstants.ORDER_REFUND_STATUS.equals(newTbBizPlaceOrder.getOrderStatus())
					&& PlaceConstants.REFUNDING_STATUS.equals(newTbBizPlaceOrder.getPayStatus())){
				//插入退款流水
				ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(newTbBizPlaceOrder,refundPrice,(byte)1,(byte)0);
				placeOrderUtilService.insertOrderHistory(reqOrderHistory);
			}
		}*/

		if (PlaceConstants.ORDER_REFUND_STATUS.equals(newTbBizPlaceOrder.getOrderStatus())
				&& PlaceConstants.REFUNDING_STATUS.equals(newTbBizPlaceOrder.getPayStatus())) {
			List<ReqOrderHistory> reqOrderHistoryList = placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(tbBizPlaceOrder, tbBizPlaceOrderItemList, (byte) 1, (byte) 0,tbBizPlaceMemberCard);
			if (!CollectionUtils.isEmpty(reqOrderHistoryList)) {
				try {
					placeOrderUtilService.shoppingCartOrderInsertOrderHistory(reqOrderHistoryList);
				} catch (Exception e) {
					e.printStackTrace();
					return APIResponse.returnFail(e.getMessage());
				}
			}
		}
		return APIResponse.returnSuccess();
	}


	/**
	 * 购物车订单扫码退款
	 * @param tbBizPlaceOrderItems
	 * @param tbBizPlaceOrder
	 * @param tbBizPlacePayItems
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public TbBizPlaceOrder shoppingCartOrderRefund(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
											  TbBizPlaceOrder tbBizPlaceOrder,
											  List<TbBizPlacePayItem> tbBizPlacePayItems) throws Exception{
		if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
			return tbBizPlaceOrder;
		}

		TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);

		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItem.getPayType().toString())
				|| PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItem.getPayType().toString())){
			/**  扫码退款 **/
			tbBizPlaceOrder = this.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
		}
		//场地订单明细
		List<TbBizPlaceOrderItem> placeUnitOrderItemList = new ArrayList<>();;
		//门票订单明细
		List<TbBizPlaceOrderItem> placeTicketOrderItemList = new ArrayList<>();
		//小商品订单明细
		List<TbBizPlaceOrderItem> placeGoodsOrderItemList = new ArrayList<>();

		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			//场地
			if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
					|| tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
					|| tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
				placeUnitOrderItemList.add(tbBizPlaceOrderItem);
			}
			//门票
			else if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
				placeTicketOrderItemList.add(tbBizPlaceOrderItem);
			}
			//小商品
			else if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
				placeGoodsOrderItemList.add(tbBizPlaceOrderItem);
			}
		}
		if (PlaceConstants.ORDER_REFUND_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
				|| PlaceConstants.REFUNDING_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
			//修改支付明细为支出类型
			TbBizPlacePayItem payItemRecord = new TbBizPlacePayItem();
			payItemRecord.setAmountType(PlaceConstants.CREDIT_TYPE);
			TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
			tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrder.getPlaceOrderId());
			tbBizPlacePayItemMapper.updateByExampleSelective(payItemRecord,tbBizPlacePayItemExample);

			if (!CollectionUtils.isEmpty(placeUnitOrderItemList)){
				//释放场地库存
				this.refundUpdateUnitSalePlan(placeUnitOrderItemList,PlaceConstants.PLACE_PREORDER_STATUS);
			}
			if (!CollectionUtils.isEmpty(placeTicketOrderItemList)){
				//修改门票统计
				placeTicketService.updateTicketStatistics(tbBizPlaceOrder, placeTicketOrderItemList);
			}
			if (!CollectionUtils.isEmpty(placeGoodsOrderItemList)){
				//增加商品库存
				placeGoodsService.addGoodsInventory(tbBizPlaceOrder,placeGoodsOrderItemList);
			}
		}
		if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
			if (!CollectionUtils.isEmpty(placeUnitOrderItemList)){
				//释放场地库存
				this.refundUpdateUnitSalePlan(placeUnitOrderItemList,PlaceConstants.PLACE_PREORDER_STATUS);
			}
			if (!CollectionUtils.isEmpty(placeTicketOrderItemList)){
				//修改门票统计
				placeTicketService.updateTicketStatistics(tbBizPlaceOrder, placeTicketOrderItemList);
			}
			if (!CollectionUtils.isEmpty(placeGoodsOrderItemList)){
				//增加商品库存
				placeGoodsService.addGoodsInventory(tbBizPlaceOrder,placeGoodsOrderItemList);
			}
		}
		return tbBizPlaceOrder;
	}


	/**
	 * 开单包场退款修改销售计划
	 * @param tbBizPlaceOrderItems
	 */
	public void refundUpdateUnitSalePlan(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,Byte status) throws Exception{
		List<String> saleIds = new ArrayList<>();
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
			saleIds.add(tbBizPlaceOrderItem.getSaleId());
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(saleIds);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = tbBizPlaceUnitSalePlanMapper
				.selectByExample(example);

		// 整点切换成半点时已预订的那部分销售计划
		TbBizPlaceUnitSalePlanExample example2 = new TbBizPlaceUnitSalePlanExample();
		example2.createCriteria().andDestSaleIdIn(saleIds);
		List<TbBizPlaceUnitSalePlan> halfTimeUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example2);
		tbBizPlaceUnitSalePlans.addAll(halfTimeUnitSalePlans);

		List<UnitSalePlan> list = new ArrayList<>();
		for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
			UnitSalePlan up = new UnitSalePlan();
			up.setSaleId(tsp.getSaleId());
			list.add(up);
		}
		ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
		reqPlaceOrderListVo.setUnitSalePlanIdList(list);
		//reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);//退款——>销售计划状态改成可预订
		reqPlaceOrderListVo.setStatus(status);
		//int flag1 = placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
		int flag1 = updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);
	}

	/** 校验购物车会员卡是否支持 **/
	@Override
	public APIResponse checkMemberCard(ReqShoppingCart reqShoppingCart) {
		reqShoppingCart.setAdminPayType(10);
		APIResponse orderInfoResponse = this.createShoppingCartOrderInfo(reqShoppingCart,false);
		if (!orderInfoResponse.isRet()){
			return orderInfoResponse;
		}
		return APIResponse.returnSuccess();
	}

	/** 扫码枪退款 **/
	@Override
	public TbBizPlaceOrder placeScanRefund(TbBizPlaceOrder tbBizPlaceOrder,
										   List<TbBizPlacePayItem> tbBizPlacePayItems,
										   List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
										   String childrenOrderId) throws Exception{
		BigDecimal refundAmount = new BigDecimal(0);
		for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItems){
			refundAmount = refundAmount.add(tbBizPlacePayItem.getAmount());
		}
		BigDecimal zeroAmount = new BigDecimal(0);
		int valid = refundAmount.compareTo(zeroAmount);
		if (valid == -1 || valid ==0){
			throw new BizException("订单金额不支持退款");
		}
		APIRequest<ReqOrderRefund> orderRefundAPIRequest = new APIRequest<>();
		ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
		//下面两个字段订单系统字段反了
		reqOrderRefund.setSourceBusinessId(Constants.PLACE_SYSTEM_CODE);
		reqOrderRefund.setSourceSystemId(Constants.PLACE_SCANPAY_CODE);
		reqOrderRefund.setOrderNo(tbBizPlaceOrder.getOrderNo());
		reqOrderRefund.setReason("百灵鸟商家端订单管理退款");
		reqOrderRefund.setUid(tbBizPlaceOrder.getCreateUid());
		reqOrderRefund.setAmount(refundAmount);
		reqOrderRefund.setNeedAudit(false); //false不需要人工审核.  true: 需要人工审核, 根据业务需求设置
		reqOrderRefund.setOutTradeNo(tbBizPlaceOrder.getPlaceOrderId());
		if (org.springframework.util.StringUtils.isEmpty(childrenOrderId)){
			reqOrderRefund.setOutTradeRefundNo(tbBizPlaceOrder.getPlaceOrderId());//业务系统退款流水号
		}else{
			reqOrderRefund.setOutTradeRefundNo(childrenOrderId);//包场退款给子订单 （原路返回更新子订单号）
		}


		List<ReqRefundProduct> reqRefundProducts = new ArrayList<>();
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
			ReqRefundProduct refundProduct = new ReqRefundProduct();
			refundProduct.setPrice(tbBizPlaceOrderItem.getSalePrice());
			refundProduct.setProductId(tbBizPlaceOrderItem.getPlaceOrderId());
			refundProduct.setQuantity(1);
			refundProduct.setProductName("百灵鸟商家端订单管理退款");
			reqRefundProducts.add(refundProduct);
		}
		reqOrderRefund.setRefundProductList(reqRefundProducts);

		List<ReqRefundPayInfo> reqRefundPayInfoList = new ArrayList<ReqRefundPayInfo>();
		ReqRefundPayInfo rmb = new ReqRefundPayInfo();
		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){
			rmb.setPayId(PayWayEnum.PAY_WAY_WEICHAT_SCAN.getPayId());
		}else if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){
			rmb.setPayId(PayWayEnum.PAY_WAY_ALIPAY_SCAN.getPayId());
		}/*else if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(tbBizPlacePayItems.get(0).getPayType().toString())){//增加商家端银联pos退款，目前银联无法提供退款接口，线下人工处理
        	 rmb.setPayId(PayWayEnum.PAY_WAY_UNION_PAY_POS.getPayId());
        }*/
		rmb.setRefundAmount(refundAmount);
		reqRefundPayInfoList.add(rmb);

		reqOrderRefund.setReqRefundPayInfos(reqRefundPayInfoList);
		orderRefundAPIRequest.setData(reqOrderRefund);
		APIResponse<RefundStatusEnum> apiResponse = orderPayService.refundApply(orderRefundAPIRequest);
		logger.debug("========================退款回调数据:reqOrderSave:{}", JSON.toJSONString(apiResponse));
		try {
			if (apiResponse == null || !apiResponse.isRet()) {
				throw new BizException(apiResponse.getErrmsg());
			}
		} catch (Exception e) {
			throw new BizException(e.getMessage());
		}
		if (RefundStatusEnum.SUCCESS.getCode().equals(apiResponse.getData().getCode())){
			//退款成功
			tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
			tbBizPlaceOrder.setPayStatus(PlaceConstants.REFUNDING_STATUS);
		}else{
			//退款申请已提交
		}
		return tbBizPlaceOrder;
	}

	/**
	 * 购物车取消预订
	 * @param reqPlaceOrderId
	 * @return
     */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void cancelShoppingCard(String reqPlaceOrderId) throws Exception{
		//查询订单
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		if(CollectionUtils.isEmpty(tbBizPlaceOrders)) {
			throw new Exception("存在重复订单");
		}
		TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrders.get(0);

		//防止重复取消
		if (tbBizPlaceOrder.getOrderStatus().intValue() != 1){
			throw new Exception("当前订单状态不支持取消");
		}

		//根据placeOrderId拿到placeOrderItem
		TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
		itemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
		itemExample.createCriteria().andUseTypeNotEqualTo(PlaceConstants.ORDER_USE_TICKET);//订单详情不包括门票
		itemExample.createCriteria().andUseTypeNotEqualTo(PlaceConstants.ORDER_USE_GOODS);//订单详情不包括商品
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
		if(CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
			throw new Exception("订单明细异常");
		}
		List<TbBizPlaceUnitSalePlan> unlockSalePlans = new ArrayList<>();
		//拿到销售计划场地Id
		for(TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
			example.createCriteria().andSaleIdEqualTo(tbBizPlaceOrderItem.getSaleId());
			//example.createCriteria().andPlaceUnitIdEqualTo(tbBizPlaceOrderItem.getUnitSalePlanId());
			List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
			unlockSalePlans.addAll(tbBizPlaceUnitSalePlans);
		}
		if (!CollectionUtils.isEmpty(unlockSalePlans)){
			// 释放库存
			refundUpdateUnitSalePlan(tbBizPlaceOrderItems, PlaceConstants.PLACE_PREORDER_STATUS);
		}

		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
		org.springframework.beans.BeanUtils.copyProperties(tbBizPlaceOrder,newTbBizPlaceOrder);
		//修改取消订单状态
		newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
		newTbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
		newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());

		TbBizPlaceOrderExample updateOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria updateOrderCriteria = updateOrderExample.createCriteria();
		updateOrderCriteria.andPlaceOrderIdEqualTo(newTbBizPlaceOrder.getPlaceOrderId());
		updateOrderCriteria.andOrderStatusEqualTo(PlaceConstants.ORDER_PREPAY_STATUS);
		updateOrderCriteria.andPayStatusEqualTo(PlaceConstants.NOT_PAY_STATUS);
		TbBizPlaceOrder updateTbBizPlaceOrder = new TbBizPlaceOrder();
		BeanUtils.copyProperties(newTbBizPlaceOrder,updateTbBizPlaceOrder);
		updateTbBizPlaceOrder.setId(null);//防止主键冲突
		if(tbBizPlaceOrderMapper.updateByExampleSelective(updateTbBizPlaceOrder,updateOrderExample) != 1){
			throw new BizException("不能重复取消订单.");
		}

		//会员取消预订
		TbBizPlaceMemberOpHistoryExample example = new TbBizPlaceMemberOpHistoryExample();
		TbBizPlaceMemberOpHistoryExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(reqPlaceOrderId);
		List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example);
		if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)){
			String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
			if(!org.springframework.util.StringUtils.isEmpty(innerCardNo)){
				TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
				TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
				tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo);
				List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
				if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList) ){
					TbBizPlaceMemberCard tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
					BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
					BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
					TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
					tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
					tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
					tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
					tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
					tbBizPlaceMemberOpHistory.setAmount(new BigDecimal(0));
					tbBizPlaceMemberOpHistory.setCreateTime(new Date());
					tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
					tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
					tbBizPlaceMemberOpHistory.setOrderNo(reqPlaceOrderId);
					tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName()+"取消");
					tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
					tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
					tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
					tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
					tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList.get(0).getMemo());
					tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
					tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
					tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
					tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
					tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
					tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
					tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
					tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
					tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());

					tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKeySelective(tbBizPlaceMemberOpHistory);
				}
			}
		}
	}

	private  BigDecimal handleDecimalNull(BigDecimal t){
		if(t==null){
			return new BigDecimal(0.0);
		}
		return t;
	}
	
	private String treeSetToString(TreeSet<String> list) {    
		StringBuffer tmp=new StringBuffer("");
	Iterator<String> iterator=list.iterator();
	while(iterator.hasNext()){
		tmp.append("'").append(iterator.next()).append("'").append(",");
	}
	String strs=tmp.toString();
	if(StringUtil.isNotBlank(strs)){
		return strs.substring(0,strs.length()-1);
	}
	return null;
	}

}
